I want to put a price on something and I get a string number and it should be divided by every 3 letters but what eve I try to do I can't is there any function or way that could be helpful ?
Asked
Active
Viewed 75 times
2 Answers
1
The simplest way is using Number#toLocaleString
with a locale. The locale en-US
uses commas to delimit every third digit and a dot to delimit the decimal fractional part.
const n = 1000000
const fractional = 12345.67
console.log(n.toLocaleString('en-US')) // 1,000,000
console.log(fractional.toLocaleString('en-US')) // 12,345.67

Lionel Rowe
- 5,164
- 1
- 14
- 27
0
Use this function:
function numWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log(numWithCommas(100000));

Wasif Shahjahan
- 346
- 2
- 9