I have a floating point number in JavaScript, like 42.563134634634. I want to display it as a string "42.56", with exactly two decimal places. How do I do that?
Asked
Active
Viewed 174 times
5 Answers
6
Use toFixed
method:
var num = 42.563134634634;
alert(num.toFixed(2));

Igor Dymov
- 16,230
- 5
- 50
- 56
-
2Wow, I've never even heard of that method before. Nice! – peirix Jul 08 '11 at 08:25
0
function roundNumber(number, decimals) { // Arguments: number to round, number of decimal places
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
return newnumber;
}

rahim asgari
- 12,197
- 10
- 43
- 53
-
1If number needs to be converted, better to see that conversion does not error. If number type is assumed, then conversion seems pointless. `parseInt(decmials)` is redundant since the first step in the *toFixed* algorithm is to call *toInteger(arg)* (ECMA-262 15.7.4.5). – RobG Jul 08 '11 at 08:34
0
Have you read this ? http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html

rails
- 161
- 2
- 4
0
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}

jasalguero
- 4,142
- 2
- 31
- 52