How to render such a number -9,521,654.35 in JavaScript ?
Requirements
- Number can be negative
- Number can have or not decimals
- Separator may change in different countries
- Solution must be JSLint certified (because that the right way of coding)
- Solution should not alter existing prototype (because this really not a good idea)
- Solution must be cross browser compatible
The solution
A very simple function base on RegExp, here it is:
/*
* thousandSeparator (NUMBER n, STRING separator) STRING
* or
* thousandSeparator (String n, STRING sep) STRING
*
* Convert a number to the format xxx,xxx,xxx.xxxx
* Accepts integers, floating point or string
*
* Does not accept exponential notation, etc.
*
* n – the number to be formatted
* sep – the separator character. if skipped, “,” is used
*/
function thousandSeparator(n,sep) {
var sRegExp = new RegExp(‘(-?[0-9]+)([0-9]{3})’),
sValue=n+”;
if (sep === undefined) {sep=’,';}
while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, ‘$1′+sep+’$2′);
}
return sValue;
}
Examples
thousandSeparator(5000) => 5,000
thousandSeparator(-5000000) => -5,000,000
thousandSeparator(5000000.125) => 5,000,000.125
thousandSeparator(5000000.125,’\”) => 5’000’000.125
Other solutions
There are many other kind of solution based on Math.foor, split of string, etc
These solutions are heavier than the RegExp solution and require much more lines of codes.



[...] came across this very simple function base on RegExp. Source 0 1 2 3 4 5 6 7 8 9 function thousandSeparator(n,sep) { var sRegExp = new [...]