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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

这个函数对我有用。你只需输入数字和你想要舍入的位置,它就可以轻松地完成所需的操作。

round(source, n) {
  let places = Math.pow(10, n);

  return Math.round(source * places) / places;
}

其他回答

这是我解决这个问题的方法:

function roundNumber(number, precision = 0) {
    var num = number.toString().replace(",", "");
    var integer, decimal, significantDigit;

    if (num.indexOf(".") > 0 && num.substring(num.indexOf(".") + 1).length > precision && precision > 0) {
        integer = parseInt(num).toString();
        decimal = num.substring(num.indexOf(".") + 1);
        significantDigit = Number(decimal.substr(precision, 1));

        if (significantDigit >= 5) {
            decimal = (Number(decimal.substr(0, precision)) + 1).toString();
            return integer + "." + decimal;
        } else {
            decimal = (Number(decimal.substr(0, precision)) + 1).toString();
            return integer + "." + decimal;
        }
    }
    else if (num.indexOf(".") > 0) {
        integer = parseInt(num).toString();
        decimal = num.substring(num.indexOf(".") + 1);
        significantDigit = num.substring(num.length - 1, 1);

        if (significantDigit >= 5) {
            decimal = (Number(decimal) + 1).toString();
            return integer + "." + decimal;
        } else {
            return integer + "." + decimal;
        }
    }

    return number;
}

在这里,我使用了三元运算符来检查数字是否具有小数。如果没有,我只需返回数字。

否则,我使用Intl.NumberFormat构造函数获取所需的值。

Intl.NumberFormat是ECMAScript国际化API规范(ECMA402)的一部分。它有很好的浏览器支持,甚至包括IE11,并且在Node.js中完全支持。

const numberFormatter=新Intl.NumberFormat('en-US'{minimumFractionDigits:2,最大分数位数:2,});函数getRoundedNumber(number){return number.toString().indexOf(“.”)==-1?number:numberFormatter.format(数字);}console.log(getRoundedNumber(10));console.log(getRoundedNumber(1.7777777));console.log(getRoundedNumber(9.1));console.log(getRoundedNumber(2.345));console.log(getRoundedNumber(2.2095));console.log(getRoundedNumber(2.995));

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

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;

虽然建议的答案通常是正确的,但没有考虑传入的数字的精度,这在原始问题中没有表示为要求,但在科学应用的情况下,这可能是一个要求,其中3不同于3.00(例如)。

事实上,建议的答案是3.001到3,而保持数字精度的信息应该是3.00。

下面是一个考虑到这一点的函数:

函数roundTo(值,十进制){让absValue=Math.abs(值);let int=数学地板(absValue).toString().length;let dec=absValue.toString().length-int;dec-=(Number.isIInteger(absValue)?0 : 1);返回值toPrecision(int+Math.min(dec,十进制));}