Tuesday, November 3, 2015

Commas as thousands separators in number in Javascript


 
For example, we want to display 1000 as 1,000.  JavaScript function  toLocaleString is used, example:
n=1000;
m=n.toLocaleString();
m will be 1,000 
If n is a string, we need to convert to number first
Number(n).toLocaleString();
 
toFixed(2) convert a number into a string, keeping only two decimals, we need to convert it to number when using  toLocaleString()
m = Number(n. toFixed(2)).toLocaleString();

No comments:

Post a Comment