Reputation: 6799
I have a string n
which is a number.
The following adds the commas where needed, but I also want to change the number of decimals. It should also round where appropriate.
var parts = n.split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
This turns a number like 1234.567
in to 1,234.567
.
But I need my number to look like: 1,234.57
I tried taking parts[1]
and converting to a Number, then rounding, then concatenating it back; but that is error prone.
How can I get this result by altering my regex? Thanks.
Upvotes: 19
Views: 55950
Reputation: 412
I think this is the easy way to format the Number with different Locale
const NumberFormatter = (value, decimal) => {
return parseFloat(parseFloat(value).toFixed(decimal)).toLocaleString(
"en-IN",
{
useGrouping: true,
}
);};
Instead of "en-IN" you can specify Language. like ‘ja-JP’,’en-US’ and ‘de-DE’, etc. It will group the number with the symbol based on the locale.
Ref: Format Numbers
Upvotes: 0
Reputation: 36511
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
Upvotes: 47
Reputation: 3845
Adding onto @Rob M's answer (for a minimum AND maximum of 2dp):
function getMe2DecimalPointsWithCommas(amount) {
return Number(amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
Upvotes: 0
Reputation: 2079
var valueString="1500"; //can be 1500.0 or 1500.00
var amount=parseFloat(valueString).toFixed(2);
var formattedString= amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(formattedString); //outputs 1,500.00
Upvotes: 1
Reputation: 538
To avoid that by converting to a number in the ternary, as zero is falsy
n = parseFloat(n).toFixed(2)
var withCommas = Number(n).toLocaleString('en');
withCommas = (withCommas.indexOf(".")== -1) ? `${withCommas}.00` : withCommas;
Upvotes: 0
Reputation: 7380
When it comes to formatting currency in JavaScript, toLocaleString is great. You don't need to combine it with toFixed
and it will not work in some cases (whole numbers, numbers with single-digit fractions). Here's an example function:
const formatCurrency = (num, locale = 'en-US', currency = 'USD', minimumFractionDigits = 2) => {
if (isNaN(num)) {
return num;
}
return num.toLocaleString(locale, {style: 'currency', currency, minimumFractionDigits});
};
No super-customized string format patterns and no chained methods that work in specific scenarios.
Here is an example fiddle
Upvotes: 0
Reputation: 280
i think this is useful
var n=1234.567
var parts = n.toFixed(2).split(".");
var num = parts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") +
(parts[1] ? "." + parts[1] : "");
console.log(num);
if you want result 1,234.567
then change toFixed(2)
to toFixed(3)
Upvotes: 1
Reputation: 6799
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] : "");
Upvotes: 8
Reputation: 318182
You could just use toFixed
var parts = (+n).toFixed(2).split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (+parts[1] ? "." + parts[1] : "");
That would also make 1234.0000
to 1234.00
, but you can avoid that by converting to a number in the ternary, as zero is falsy
Upvotes: 3