JavaScript/Digit grouping
Appearance
Digits can be grouped in JavaScript by inserting separation characters after as many digits as the length of a digit group. Typically, the separation character is a comma (,
), and there are three digits per group. The process of inserting separation characters is repeated as many times as the number's length divided by the length of a digit group, and that count is floored (rounded down).
The script also verifies whether the input is valid, and avoids placing a trailing separation character after the number.
The code below is commented to help you understand the purposes of individual lines.
function digit_grouper(
// The order of the second and third parameter can be swapped if desired, but input_number should be at the beginning.
input_number, digits_per_group, digit_separator
) {
// defaults
if ( isNaN(input_number) ) return false; // return on invalid input
if (!digit_separator) digit_separator=","; // separation character if none specified
if (!digits_per_group || isNaN(input_number) ) digits_per_group=3; // digits per group if none specified
// prepending empty strings before numbers to force variable type into "string" instead of "number"
var input_length = (""+input_number).length; // memorize length of input number
var output = "" + input_number; // initiating output variable
var count; // defeats JSHint error; no functional difference.
if (input_length > digits_per_group && Math.floor(digits_per_group) > 0) /* skip grouping digits if shorter than digits per group; prevent division by zero that would lead to infinite loop */ {
// insert "+1" after the first "digits_per_group" above in order to not group four-digit numbers like YouTube occasionally did on their mobile web site.
for (
count=1; // start counter at 1 to prevent trailing comma in slice
count-1 < Math.floor( (input_length-1)/digits_per_group ) && count < 1000; // repeat splicing as many times as digit groups will be created. Limit to 1000 cycles for "sanity", i.e. to safe-guard against an endless loop should one occur due to possible undiscovered bugs. A user is anyway very unlikely to specify a number that long. Should it actually be necessary, this restriction can be altered.
count++ // count up for each pass
) {
output = output.substring(0,input_length-(count*digits_per_group) ) + digit_separator + output.substring(input_length-(count*digits_per_group) ); // insert separator
}
}
return output;
}