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
Answer from Rob M. on Stack OverflowEdit: 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] : "");
I am trying to format a number like this 250,000.50
What I have tried
<td style="text-align:right;">${{"{0:,.2f}"|format(data[0]['amount']) }} </td>
<td style="text-align:right;">${{"{:0.2f}"|format(data[0]['amount']) }} </td>
<td style="text-align:right;">${{"{0:%.2f}"|format(data[0]['amount']) }} </td>
data[0]['amount']contains 250000.505050