我有以下JavaScript语法:

var discount = Math.round(100 - (price / listprice) * 100);

这是整数。我如何返回两个小数点后的结果?


当前回答

下面是一个工作示例

var value=200.2365455;
result=Math.round(value*100)/100    //result will be 200.24

其他回答

要得到两个小数的结果,你可以这样做:

var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;

要四舍五入的值乘以100以保留前两位数字,然后除以100以得到实际结果。

我找到的最好最简单的解决办法是

function round(value, decimals) {
 return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}   
round(1.005, 2); // 1.01
function round(num,dec)
{
    num = Math.round(num+'e'+dec)
    return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)

尝试使用discount.toFixed(2);

对公认答案的一个小变化。 toFixed(2)返回一个字符串,你将总是得到两个小数点后的位置。这些可能是零。如果你想压制最后的0 (s),简单地这样做:

var discount = + ((price / listprice).toFixed(2));

编辑: 我刚刚在Firefox 35.0.1中发现了一个错误,这意味着上面可能会给NaN一些值。 我把代码改成了

var discount = Math.round(price / listprice * 100) / 100;

这给出了一个小数点后最多两位的数字。如果你想要3个,你可以乘除1000,以此类推。 OP总是需要两个小数点后的位置,但是如果toFixed()在Firefox中被破坏了,它首先需要修复。 参见https://bugzilla.mozilla.org/show_bug.cgi?id=1134388