I have a floating point number in JavaScript, like 42.5开发者_开发百科63134634634. I want to display it as a string "42.56", with exactly two decimal places. How do I do that?
Use toFixed
method:
var num = 42.563134634634;
alert(num.toFixed(2));
You could do
var num = 42.563134634634;
var res = num.toFixed(2);
function roundNumber(number, decimals) { // Arguments: number to round, number of decimal places
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
return newnumber;
}
Have you read this ? http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
精彩评论