9

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.

Jonathan Bechtel
  • 3,497
  • 4
  • 43
  • 73
  • Could you test to see how many numbers are after the decimal, and if its only one, add a 0 to the end of it? – Ian Wise May 07 '15 at 17:45
  • try this regex to append 0 if single digit after decimal: `parseFloat((num).toFixed(2)).toLocaleString().replace(/\.([0-9])$/, ".$10")` – gp. May 07 '15 at 18:00

1 Answers1

7

This seems to work

var formatNumber = function(num) {
    return parseFloat(num).toFixed(2).toLocaleString();
};
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Katya Pavlenko
  • 3,303
  • 3
  • 16
  • 28
  • 10
    This doesn't work for whole numbers. See this [fiddle](http://jsfiddle.net/razs3mjb/) – Ken Gregory Oct 21 '17 at 16:30
  • 1
    @KenGregory No desire to be a necromancer but you placed `toFixed()` inside `parseFloat()` in your fiddle and that's why it failed for you. If you move it outside, it works fine, and you can also do away with the `replace`. [Forked fiddle](http://jsfiddle.net/4j95hroy/). – Dan Atkinson Dec 17 '21 at 09:52
  • 2
    @DanAtkinson thanks! My overdue apologies to Katya Pavlenko - I was wrong here. – Ken Gregory Dec 17 '21 at 14:32
  • I ran into issues with this approach because .toFixed() will turn your number into a string and then running toLocaleString() on that doesn't have the desired effect of adding the commas. I found the approach in this answer worked well though. Just adding in case others run into a similiar issue. https://stackoverflow.com/a/48653557/402780 – Komeisa Jun 02 '23 at 19:35