regex format string number with commas and 2 decimals in javascript
Edit: Sept 18, 2019
Since new APIs are available, thought it would be helpful to point out that you can do this much more simply using toLocaleString
options:
const numbers = [1, 1000, 2345.67, 21589.334719999995];
const options = {
minimumFractionDigits: 2,
maximumFractionDigits: 2
};
numbers.forEach(num => {
const formatted = Number(num).toLocaleString('en', options);
console.log(formatted);
});
original answer
To add the commas, you could use:
n = parseFloat(n).toFixed(2)
var withCommas = Number(n).toLocaleString('en');
Here is a fiddle
var val = Math.round(Number(n) *100) / 100;
var parts = val.toString().split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");