3

How can I convert a integer type to a double/float type so it shows decimal points? For instance if I want to convert a number to a money format:

5 would turn into 5.00 4.3 would turn into 4.30

Does javascript have something I can use to do this kind of conversion?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Howdy_McGee
  • 10,036
  • 28
  • 103
  • 179

2 Answers2

3

You want toFixed:

var a = 5;
a.toFixed(2); // '5.00'
4.3.toFixed(2); // '4.30'
Joe
  • 77,580
  • 18
  • 124
  • 143
1

You can use toFixed(n), where n is the number of decimal places.

5 .toFixed(2);
//-> "5.00"

4.3 .toFixed(2);
//-> "4.30"
Andy E
  • 326,646
  • 82
  • 467
  • 441
  • 1
    @IAbstract: I wouldn't really say that's relevant, since it would be a rare occasion where you would write it out like this. Normally, you would call `toFixed()` on a variable, otherwise you may as well just write the number as a string literal in the first place. – Andy E Sep 09 '11 at 23:45