How to separate number thousands in Javascript?
You can use the toLocaleString() method to comma-separate thousands in a number for a given localization, such as 'en-US'. You can also use the Intl. NumberFormatter object to format a number to a specific localization. Lastly, you can also build your own custom function to get the job done.
function commify(n) {
var parts = n.toString().split(".");
const numberPart = parts[0];
const decimalPart = parts[1];
const thousands = /\B(?=(\d{3})+(?!\d))/g;
return numberPart.replace(thousands, ",") + (decimalPart ? "." + decimalPart : "");
}
Output
ommify(9010173.1293) // Returns '9,010,173.1293'