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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

精确的舍入方法。来源: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

其他回答

这项看似简单的任务面临的最大挑战是,我们希望它能够产生心理预期的结果,即使输入包含最小的舍入误差(更不用说计算中会出现的误差)。如果我们知道实际结果正好是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。如果您仍然需要支持它,那么您可以使用垫片,或者自己定义特定浏览器系列的常量。

避免舍入到任意位数的二进制问题的适当方法是:

function roundToDigits(number, digits) {
  return Number(Math.round(Number(number + 'e' + digits)) + 'e-' + digits);
}

修复toFixed()函数的一种方法是:

Number.prototype.toFixed = (prototype => {
    const toFixed = prototype.toFixed;

    // noinspection JSVoidFunctionReturnValueUsed
    return function (fractionDigits) {
        if (!fractionDigits) {
            return toFixed.call(this);
        } else {
            // Avoid binary rounding issues
            fractionDigits = Math.floor(fractionDigits);
            const n = Number(Math.round(Number(+this + 'e' + fractionDigits)) + 'e-' + fractionDigits);
            return toFixed.call(n, fractionDigits);
        }
    };
})(Number.prototype);

与Brian Ustas建议的使用Math.round不同,我更喜欢Math.trunc方法来解决以下问题:

const twoDecimalRound = num => Math.round(num * 100) / 100;
const twoDecimalTrunc = num => Math.trunc(num * 100) / 100;
console.info(twoDecimalRound(79.996)); // Not desired output: 80;
console.info(twoDecimalTrunc(79.996)); // Desired output: 79.99;

一个助手函数,其中rounding是默认舍入:

let rounding = 4;

let round = (number) => { let multiply = Math.pow(10,rounding);  return Math.round(number*multiply)/multiply};

console.log(round(0.040579431));

=> 0.0406

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

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

// 123.46