17

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

11 => 11.00

45 => 45.00

Please help me.

Thank you.

2
  • possible duplicate of JavaScript: formatting number with exactly two decimals Commented Jul 27, 2012 at 9: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 Commented Jul 27, 2012 at 9:48

4 Answers 4

41

Use .toFixed:

var num = 45;
num.toFixed(2); //"45.00"
Sign up to request clarification or add additional context in comments.

1 Comment

It should be mentioned that the return value will be a string and not a float
4
var num = 10;
var result = num.toFixed(2);

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

Comments

3

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"

Comments

0

Just add toFixed(2) here with your variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.