14

I am trying to convert numbers into comma separated format with two decimal places for each and every number in javascript:

My code:

Number(parseFloat(n).toFixed(2)).toLocaleString('en');

This code doesn't show two decimal places (.00) for whole numbers.

I am expecting following results for a set of numbers:

10000 => 100,00.00
123233.12 => 123,233.12
300000.5  => 300,000.50

Appreciate your answer, thanks.

Božo Stojković
  • 2,813
  • 1
  • 22
  • 50
SatAj
  • 1,809
  • 4
  • 28
  • 44
  • Take a look at this question - http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript?rq=1 – mattferderer Jul 19 '16 at 15:25

1 Answers1

32

You can use the minimumFractionDigits option of the toLocaleString function.

// result 3,000.00
Number(parseFloat(3000).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

// result 123,233.12
Number(parseFloat(123233.12).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

You can even remove the parseFloat,toFixed and Number function usage as well, if this is not used for some logic other than displaying the decimal value up to 2 digits.

Deep
  • 9,344
  • 2
  • 17
  • 31
  • Thank you very much for your solution – Udara Apr 06 '18 at 04:14
  • 1
    Note that this only works for the locale 'en'. I tried to use another locale to replace the separator dot with a comma but that does not work, unfortunately. – Jurrian Mar 28 '19 at 08:45