Last active
December 13, 2015 22:28
-
-
Save roxeteer/4984159 to your computer and use it in GitHub Desktop.
JavaScript: Add thousands separators
This file contains 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
// add separators to any kind of a number | |
function sep(val) { | |
if (!val) return val; | |
var s = val + "", | |
components = s.split("."), | |
x = components[0].split(""); | |
for (var i = x.length - 3; i > 0; i -= 3) { | |
x.splice(i, 0, ","); | |
} | |
return [x.join("")].concat(components.slice(1)).join("."); | |
} | |
// please note that JavaScript automatically removes trailing zeros to the right | |
// of a decimal point (e.g. sep(1000.0) -> "1,000") | |
// if you want to make sure your trailing zeros are left intact, pass the value | |
// as a string (e.g. sep("1000.0") -> "1,000.0") | |
sep(10000.5); // -> "10,000.5" | |
sep(123456.78); // -> "123,456.78" | |
sep(999.00); // -> "999" |
This file contains 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
// add separators to an integer | |
function sep(val) { | |
var x = (val + "").split(""); | |
for (var i = x.length - 3; i > 0; i -= 3) { | |
x.splice(i, 0, ","); | |
} | |
return x.join(""); | |
} | |
sep(10000); // -> "10,000" | |
sep(123456); // -> "123,456" | |
sep(999); // -> "999" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment