我有以下JavaScript语法:

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

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


当前回答

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

两位小数

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

三位小数

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

其他回答

最快的方式-比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

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

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

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

我认为我见过最好的方法是乘以10的位数次方,然后做个数学。四舍五入,最后除以10的数字次方。下面是我在typescript中使用的一个简单函数:

function roundToXDigits(value: number, digits: number) {
    value = value * Math.pow(10, digits);
    value = Math.round(value);
    value = value / Math.pow(10, digits);
    return value;
}

或者纯javascript:

function roundToXDigits(value, digits) {
    if(!digits){
        digits = 2;
    }
    value = value * Math.pow(10, digits);
    value = Math.round(value);
    value = value / Math.pow(10, digits);
    return value;
}

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

例如:+ discount.toFixed (2)