我有以下JavaScript语法:

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

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


当前回答

下面是一个工作示例

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

其他回答

最快的方式-比toFixed()快:

两位小数

x      = .123456
result = Math.round(x * 100) / 100  // result .12

三位小数

x      = .123456
result = Math.round(x * 1000) / 1000      // result .123

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

function round(value, decimals) {
 return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}   
round(1.005, 2); // 1.01

对公认答案的一个小变化。 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

如果使用一元加号将字符串转换为MDN上记录的数字。

例如:+ discount.toFixed (2)

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)