Last active
August 29, 2015 13:55
-
-
Save kcassam/8775329 to your computer and use it in GitHub Desktop.
I'm aware of phpjs.org, but I made a better number_format with better functionalities : I added a 'strip' parameter to say if you want non significant 0 to be striped (9,100 = 9,1), and I changed default values to make them like I want them
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
/* inspired by | |
http://phpjs.org/functions/number_format/ | |
http://stackoverflow.com/questions/5731193/how-to-format-numbers-using-javascript | |
http://stackoverflow.com/questions/7312468/javascript-round-to-a-number-of-decimal-places-but-strip-extra-zeros | |
*/ | |
function better_number_format(number, decimals, dec_point, thousands_sep, strip) | |
{ | |
// default values | |
decimals = (typeof decimals === "undefined") ? 1 : decimals; | |
dec_point = (typeof dec_point === "undefined") ? '.' : dec_point; | |
/* I use a no-break-space character as default thousands separator http://www.fileformat.info/info/unicode/char/00a0/index.htm */ | |
thousands_sep = (typeof thousands_sep === "undefined") ? ' ' : thousands_sep; | |
strip = (typeof strip === "undefined") ? 1 : strip; | |
// let's go | |
number = (number).toFixed(decimals); | |
number = strip ? parseFloat(number): number; | |
nStr = number+''; | |
x = nStr.split('.'); | |
x1 = x[0]; | |
x2 = x.length > 1 ? dec_point + x[1] : ''; | |
var rgx = /(\d+)(\d{3})/; | |
while (rgx.test(x1)) { | |
x1 = x1.replace(rgx, '$1' + thousands_sep + '$2'); | |
} | |
return x1 + x2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment