我想最多四舍五入两位小数,但只有在必要时。

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

为了记录在案,如果要舍入的数字和位数足够大,缩放方法理论上可以返回无穷大。在JavaScript中,这应该不是问题,因为最大数字是1.7976931348623157e+308,但如果您使用的是非常大的数字或很多小数位数,您可以尝试使用此函数:

Number.prototype.roundTo=函数(数字){var str=this.toString();var split=this.toString().split('e');var scientific=split.length>1;var指数;if(科学){str=拆分[0];var decimal=str.split('.');如果(小数长度<2)返回此;index=十进制[0]。长度+1+位;}其他的index=Math.floor(this).toString().length+1+位数;if(str.length<=索引)返回此;var数字=str[index+1];var num=Number.parseFloat(str.substring(0,索引));如果(数字>=5){var extra=数学.pow(10,-位);返回此<0?num-额外:num+额外;}if(科学)num+=“e”+拆分[1];返回num;}

其他回答

最简单的方法:

+num.to固定(2)

它将其转换为字符串,然后再转换为整数/浮点。

在Node.js环境中,我只使用roundTo模块:

const roundTo = require('round-to');
...
roundTo(123.4567, 2);

// 123.46

从现有的答案中,我找到了另一个似乎很有效的解决方案,它也可以发送字符串,并消除尾随零。

function roundToDecimal(string, decimals) {
    return parseFloat(parseFloat(string).toFixed(decimals));
}

如果你派一些公牛来,那就不算什么了。。就像“阿帕”一样。或者它可能会抛出一个错误,我认为这是正确的方法。无论如何,隐藏应该修复的错误(通过调用函数)是不好的。

使用Math.rround():

Math.round(num * 100) / 100

或者更具体地说,为了确保1.005这样的数字正确,请使用Number.EPSILON:

Math.round((num + Number.EPSILON) * 100) / 100

这是astorije的答案的修改版本,更好地支持负值舍入。

// https://stackoverflow.com/a/21323513/384884
// Modified answer from astorije
function round(value, precision) {
    // Ensure precision exists
    if (typeof precision === "undefined" || +precision === 0) {
        // Just do a regular Math.round
        return Math.round(value);
    }

    // Convert the value and precision variables both to numbers
    value = +value;
    precision = +precision;

    // Ensure the value is a number and that precision is usable
    if (isNaN(value) || !(typeof precision === "number" && precision % 1 === 0)) {
        // Return NaN
        return NaN;
    }

    // Get the sign of value
    var signValue = Math.sign(value);

    // Get the absolute value of value
    value = Math.abs(value);

    // Shift
    value = value.toString().split("e");
    value = Math.round(+(value[0] + "e" + (value[1] ? (+value[1] + precision) : precision)));

    // Shift back
    value = value.toString().split("e");
    value = +(value[0] + "e" + (value[1] ? (+value[1] - precision) : -precision));

    // Apply the sign
    value = value * signValue;

    // Return rounded value
    return value;
}