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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

这里找到的答案都不正确。臭柴塞曼要求四舍五入,但你们都四舍五进。

要进行汇总,请使用以下命令:

Math.ceil(num * 100)/100;

其他回答

这项看似简单的任务面临的最大挑战是,我们希望它能够产生心理预期的结果,即使输入包含最小的舍入误差(更不用说计算中会出现的误差)。如果我们知道实际结果正好是1.005,那么我们预计舍入到两位数会得到1.01,即使1.005是一个带有大量舍入误差的大型计算的结果。

当处理floor()而不是round()时,问题变得更加明显。例如,当删除33.3点后面的最后两位数字后的所有内容时,我们肯定不会期望得到33.29,但这就是结果:

console.log(数学楼层(33.3*100)/100)

在简单的情况下,解决方案是对字符串而不是浮点数执行计算,从而完全避免舍入错误。然而,这个选项在第一次非平凡的数学运算(包括大多数除法运算)时失败,而且速度很慢。

当对浮点数进行操作时,解决方案是引入一个参数,该参数指定我们愿意偏离实际计算结果的量,以便输出心理预期的结果。

var round=函数(num,数字=2,compensateErrors=2){如果(num<0){return this.round(-num,数字,compensateErrors);}const pow=数学.pow(10,数字);return(数学舍入(num*pow*(1+compensateErrors*Number.EPSILON))/pow);}/*---测试---*/console.log(“本线程中提到的边缘案例:”)var值=[0.015,1.005,5.555,156893.145,362.42499999999995,1.275,1.277499,1.2345678e+2,2.175,5.015,58.9*0.15];值。对于每个((n)=>{console.log(n+“->”+圆(n));console.log(-n+“->”+圆形(-n));});console.log(“\n对于太大以至于无法在计算精度范围内执行舍入的数字,只有基于字符串的计算才有帮助。”)console.log(“标准:”+圆形(1e+19));console.log(“补偿=1:”+圆(1e+19,2,1));console.log(“有效无补偿:”+round(1e+19,2,0.4));

注意:Internet Explorer不知道Number.EPSILON。如果您仍然需要支持它,那么您可以使用垫片,或者自己定义特定浏览器系列的常量。

MarkG的答案是正确的。这里是任何小数位数的通用扩展。

Number.prototype.round = function(places) {
  return +(Math.round(this + "e+" + places)  + "e-" + places);
}

用法:

var n = 1.7777;    
n.round(2); // 1.78

单元测试:

it.only('should round floats to 2 places', function() {
    
  var cases = [
    { n: 10,      e: 10,    p:2 },
    { n: 1.7777,  e: 1.78,  p:2 },
    { n: 1.005,   e: 1.01,  p:2 },
    { n: 1.005,   e: 1,     p:0 },
    { n: 1.77777, e: 1.8,   p:1 }
  ]
    
  cases.forEach(function(testCase) {
    var r = testCase.n.round(testCase.p);
    assert.equal(r, testCase.e, 'didn\'t get right number');
  });
})

使用Math.rround():

Math.round(num * 100) / 100

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

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

最简单的方法:

+num.to固定(2)

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

精确的舍入方法。来源:Mozilla

(function(){

    /**
     * Decimal adjustment of a number.
     *
     * @param   {String}    type    The type of adjustment.
     * @param   {Number}    value   The number.
     * @param   {Integer}   exp     The exponent (the 10 logarithm of the adjustment base).
     * @returns {Number}            The adjusted value.
     */
    function decimalAdjust(type, value, exp) {
        // If the exp is undefined or zero...
        if (typeof exp === 'undefined' || +exp === 0) {
            return Math[type](value);
        }
        value = +value;
        exp = +exp;
        // If the value is not a number or the exp is not an integer...
        if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
            return NaN;
        }
        // Shift
        value = value.toString().split('e');
        value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
        // Shift back
        value = value.toString().split('e');
        return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
    }

    // Decimal round
    if (!Math.round10) {
        Math.round10 = function(value, exp) {
            return decimalAdjust('round', value, exp);
        };
    }
    // Decimal floor
    if (!Math.floor10) {
        Math.floor10 = function(value, exp) {
            return decimalAdjust('floor', value, exp);
        };
    }
    // Decimal ceil
    if (!Math.ceil10) {
        Math.ceil10 = function(value, exp) {
            return decimalAdjust('ceil', value, exp);
        };
    }
})();

示例:

// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50