User:Elominius mobile/digit grouper.js

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; // prepending empty strings before numbers to force variable type into string 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; }