Ram Rachum
Ram Rachum

Reputation: 88508

Rounding a float in JavaScript

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?

Upvotes: 4

Views: 180

Answers (5)

jasalguero
jasalguero

Reputation: 4181

function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

Upvotes: 0

Aleks G
Aleks G

Reputation: 57306

You could do

var num = 42.563134634634;
var res = num.toFixed(2);

Upvotes: 2

Igor Dymov
Igor Dymov

Reputation: 16460

Use toFixed method:

var num = 42.563134634634;
alert(num.toFixed(2));

Upvotes: 6

rahim asgari
rahim asgari

Reputation: 12437

function roundNumber(number, decimals) { // Arguments: number to round, number of decimal places
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return newnumber;
}

Upvotes: 0

Related Questions