4

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?

Ram Rachum
  • 84,019
  • 84
  • 236
  • 374

5 Answers5

6

Use toFixed method:

var num = 42.563134634634;
alert(num.toFixed(2));
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
2

You could do

var num = 42.563134634634;
var res = num.toFixed(2);
Aleks G
  • 56,435
  • 29
  • 168
  • 265
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
  • 1
    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). – RobG Jul 08 '11 at 08:34
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