Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting numbers for commas and decimal places with Javascript [duplicate]

Tags:

javascript

I'm trying to create a function with javascript that displays all numbers with two decimal points and adds commas every three digits (1,000 10,000 100,000 etc).

At first I had this:

var formatNumber = function(num) {
    return parseFloat((num).toFixed(2)).toLocaleString();
};

This works very well but with one exception.

1.2 != 1.20 in the final output. It just shows up as 1.2

But everything else is good. 124.5879697 = 124.59, 10000 = 10,000, and 10586.357 = 10,586.36

The issue is the final output is going to display as money, so displaying 10000 as $10,000 is fine. But displaying 1.2 as $1.2 looks a little off.

To get around this I tried to add the following modification:

var formatNumber = function(num) {
   return parseFloat((Math.round(num*100)/100)).toFixed(2).toLocaleString();
};

This carries everything out to two decimal places, which is fine, but it seems to have de-activated toLocaleString because now nothing displays commas.

I'm looking to use pure Javascript with this and not jQuery. It seems there are a lot of js questions on this topic about one or the other issue, but not combining both.

Thank you.

like image 770
Jonathan Bechtel Avatar asked May 07 '15 17:05

Jonathan Bechtel


1 Answers

This seems to work

var formatNumber = function(num) {
    return parseFloat(num).toFixed(2).toLocaleString();
};
like image 103
Katya Pavlenko Avatar answered Oct 29 '22 09:10

Katya Pavlenko