Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Format whole numbers using toLocaleString()

Tags:

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.

like image 759
Keven Avatar asked Feb 03 '14 20:02

Keven


People also ask

Does toLocaleString round?

The toLocaleString() method will round the resulting value if necessary. The toLocaleString() method does not change the value of the original number.

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.

What does the toLocaleString () method do in JS?

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .


1 Answers

How about:

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:

const sum = 1000;  const formatted = sum.toLocaleString("en", {     style: "currency",     currency: "USD",     minimumFractionDigits: 0,     maximumFractionDigits: 0, });  console.log(formatted); 

for:

// $1,000 
like image 115
Guy Avatar answered Nov 21 '22 16:11

Guy