Reputation: 88508
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
Reputation: 4181
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
Upvotes: 0
Reputation: 161
Have you read this ? http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html
Upvotes: 0
Reputation: 57306
You could do
var num = 42.563134634634;
var res = num.toFixed(2);
Upvotes: 2
Reputation: 16460
Use toFixed
method:
var num = 42.563134634634;
alert(num.toFixed(2));
Upvotes: 6
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