How to render such a number -9,521,654.35 in JavaScript ?
Requirements
- Number can be negative
- Number can have or not decimals
- Decimal can have more than 3 digits
- Separator may change in different countriesbut is optional
- Decimal Separator may change in different countries but is optional
- 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 simple function base on RegExp, here it is:
/*
* AddThousandSeparator (NUMBER n, STRING thousandSeparator, STRING decimalSeparator) STRING
* or
* AddThousandSeparator (String n, STRING thousandSeparator, STRING decimalSeparator) 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
* thousandSeparator – the separator character. if skipped, “,” is used
* decimalSeparator – the separator character. if skipped, “.” is used
*/
function AddThousandSeparator(str, thousandSeparator, decimalSeparator) {
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
sValue = str + "", // to be sure we are dealing with a string
arrNum = [];
if (thousandSeparator === undefined) {thousandSeparator = “,”; }
if (decimalSeparator === undefined) {decimalSeparator = “.”; }
arrNum = sValue.split(decimalSeparator);
// let’s be focused first only on the integer part
sValue = arrNum[0];
while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, ‘$1’ + thousandSeparator + ‘$2’);
}
// time to add back the decimal part
if (arrNum.length > 1) {
sValue = sValue + decimalSeparator + arrNum[1];
}
return sValue;
}
Examples
AddThousandSeparator(5000) => 5,000
AddThousandSeparator(-5000000) => -5,000,000
AddThousandSeparator(5000000.125) => 5,000,000.125
AddThousandSeparator(5000000.125,’\”) => 5’000’000.125
AddThousandSeparator(1234345.345545) => 1,234,345.345545
AddThousandSeparator(“123456789,12345″,’\”,”,”) => 123’456’789,12345
AddThousandSeparator(-123456789.123456789) => -123,456,789.12345679
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 […]