Created
April 18, 2013 03:48
-
-
Save physacco/5409946 to your computer and use it in GitHub Desktop.
Print number in comma-splited format in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Print number in comma-splited format. | |
// Written by physacco. 2011-05-13. | |
// | |
// Tested on: | |
// - Mozilla SpiderMonkey JavaScript-C 1.7.0 2007-10-03. | |
// - Mozilla Rhino 1.7 release 0.7.r2.fc12 2009 07 28. | |
function commaSplitNumber(num) { | |
var numstr = num.toString(); | |
var dec, frac; | |
var tmp = numstr.split("."); | |
dec = tmp[0]; | |
frac = tmp[1]; | |
var dec_len = dec.length; | |
var loop_rem = dec_len % 3; | |
var loop_max = (dec_len - loop_rem) / 3; | |
var segs = []; | |
for(var i = 0; i < loop_max; i++) { | |
var end = dec_len - i * 3; | |
var beg = end - 3; | |
var sub = numstr.substring(beg, end); | |
segs.unshift(sub); | |
} | |
if(loop_rem) { | |
segs.unshift(numstr.substring(0, loop_rem)); | |
} | |
var ret = segs.join(","); | |
if(frac) { | |
ret += "." + frac; | |
} | |
return ret; | |
} | |
// To run it with nodejs, substitute print with console.log. | |
print(commaSplitNumber("123456")); | |
print(commaSplitNumber("12345678")); | |
print(commaSplitNumber("12345678.12345")); | |
// Output: | |
// 123,456 | |
// 12,345,678 | |
// 12,345,678.12345 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment