Advertisement
Guest User

Digit grouper (revision 2022-08-03)

a guest
Aug 6th, 2022
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function digit_grouper(
  2.     // The order of the second and third parameter can be swapped if desired, but input_number should be at the beginning.
  3.     input_number, digits_per_group, digit_separator
  4.     ) {
  5.         // defaults
  6.     if ( isNaN(input_number) ) return false; // return on invalid input
  7.     if (!digit_separator) digit_separator=","; // separation character if none specified
  8.     if (!digits_per_group || isNaN(input_number) ) digits_per_group=3; // digits per group if none specified
  9.         // prepending empty strings before numbers to force variable type into "string" instead of "number"
  10.     var input_length = (""+input_number).length; // memorize length of input number
  11.     var output = "" + input_number; // initiating output variable
  12.     var count; // defeats JSHint error; no functional difference.
  13.     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 */ {
  14.         // 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.
  15.         for (
  16.             count=1; // start counter at 1 to prevent trailing comma in slice
  17.             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.
  18.             count++ // count up for each pass
  19.         ) {
  20.             output = output.substring(0,input_length-(count*digits_per_group) ) + digit_separator + output.substring(input_length-(count*digits_per_group) ); // insert separator
  21.         }
  22.     }
  23.     return output;
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement