4

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,753
  • 72
  • 57
  • 129
Howdy_McGee
  • 10,422
  • 29
  • 111
  • 186

2 Answers2

4

You want toFixed:

var a = 5;
a.toFixed(2); // '5.00'
4.3.toFixed(2); // '4.30'
Joe
  • 80,724
  • 18
  • 127
  • 145
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
  • 338,112
  • 86
  • 474
  • 445
  • 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