JavaScript: Format whole numbers using toLocaleString()
javascript
Solution
How about toLocaleString:
const sum = 1000;
const formatted = sum.toLocaleString("en", {
minimumFractionDigits: 0,
maximumFractionDigits: 0,
});
console.log(formatted);
for:
// 1,000
Or if you're into the money stuff:
const sum = 1000;
const formatted = sum.toLocaleString("en", {
style: "currency",
currency: "USD",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
});
console.log(formatted);
for:
// $1,000
Replace `"en"` with one of the supported language tags*. For instance:
'en-US'
// en => a BCP 47 tag that represents a language
// US => a ISO_3166-1 Alpha-2 subtag that represents a country | optional
Replace `"USD"` with a ISO-4217 currency code. For instance:
'EUR'
// EUR is currency #978 on the active currencies codes list.
// The result would be a numeric value prefixed by the € sign
* Further information is available on the BCP 47 and ISO 3166-1 wikis.
Problem
I'm using the `Number.prototype.toLocaleString()` function to add commas to whole numbers. Documentation for it can be found here. I am writing it as follows: ``` Number(data).ToLocaleString('en'); ``` In Firefox/Chrome the number is displayed like `123,456,789`. However, in IE it is displayed like `123,456,789.00`. 1. Why is IE adding in the decimal point values? 2. How can I remove the decimal point values? Rather than creating/using a custom function, I'm really just wondering if there is an option that I can add to ToLocaleString() like `en, nodecimal`. If that option is not available, I will consider a custom function.