'How to do thousand comma separator for javascript calculator?
I'm trying to make a thousand comma separator for JavaScript calculator.
But something works weird for me.
Here is the code that should work:
var commas = result.textContent.toLocaleString("en-US");
var commas = result.textContent.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
result.innerHTML=commas;
It works only for 1st separator, but when it goes further it looks weird. What am I doing wrong?
Here are the screenshots: image1 image2
Here is the link to calculator:
https://codesandbox.io/s/thirsty-rgb-2rp6dv?file=/js/script.js
UPD: If there's more than 4 numbers it shows NaN: NaN error
Thank you in advance!
Solution 1:[1]
Try to use Intl.NumberFormat
number = 100003.56
console.log(new Intl.NumberFormat('en-US').format(number));
Refer docs here for more
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ????? ??????? |