Advertisement
Guest User

digit grouper

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