15

I want to convert the integer to floating number with precision 2. ie. -

11 => 11.00

45 => 45.00

Please help me.

Thank you.

teenu
  • 684
  • 2
  • 8
  • 24
  • possible duplicate of [JavaScript: formatting number with exactly two decimals](http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals) – Esailija Jul 27 '12 at 09:47
  • you have to explain more, if you want the conversion for display purposes, 11 + ".00" will do. If you convert interger to float, the decimal places are always 0 – Jacob George Jul 27 '12 at 09:48

4 Answers4

38

Use .toFixed:

var num = 45;
num.toFixed(2); //"45.00"
Esailija
  • 138,174
  • 23
  • 272
  • 326
3
var num = 10;
var result = num.toFixed(2);

http://www.mredkj.com/javascript/nfbasic2.html

user1236048
  • 5,542
  • 7
  • 50
  • 87
2

This a very common problem I see someone has already answered, I want to add to it, if you want to further use the number after conversion for calculations Try this in console

a = 10.2222;
console.log(typeof a) // "number"
console.log(a)        // 10.2222 

b = parseFloat(a).toFixed(2);
console.log(typeof b) // "String"
console.log(b)        // "10.22"

c = parseFloat(b)
console.log(typeof c) // "number"
console.log(c)        // 10.22

Explanation is-

toFixed() method outputs a string variable
but if you want to further use the value of b as a 'number'
you will have to, 
c = parseFloat(b)
typeof c
// "number"
vegemite4me
  • 6,621
  • 5
  • 53
  • 79
Yash Rahurikar
  • 186
  • 1
  • 10
0

Just add toFixed(2) here with your variable.

Abdus Salam Azad
  • 5,087
  • 46
  • 35