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?
5 Answers
Use toFixed method:
var num = 42.563134634634;
alert(num.toFixed(2));
1 Comment
peirix
Wow, I've never even heard of that method before. Nice!
function roundNumber(number, decimals) { // Arguments: number to round, number of decimal places
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
return newnumber;
}
1 Comment
RobG
If 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).Have you read this ? http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html