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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

当我想一直舍入到某个小数点时,这对我来说非常有效。这里的关键是,我们将始终使用Math.ceil函数进行舍入。

如果需要,可以有条件地选择天花板或地板。

/***在大量数据时可能失去精度*@param编号*@return数字*/var roundUpToNearestHundredth=函数(数字){//确保我们使用高精度数字number=数量(number);//保存原始数字,这样当我们提取第一百位小数时,就不会进行位切换或丢失精度var numberSave=数字(Number.toFixed(0));//删除数字顶部的“整数”值number=number-number保存;//获取小数点后一百位数量*=100;//终止小数。因此,15000001将等于151等。number=数学ceil(数字);//把小数放回正确的位置数量/=100;//将“整数”加回到数字上return number+numberSave;};console.log(roundUpToNearestHundredth(6132423.1200000000001))

其他回答

有两种方法可以做到这一点。对于像我这样的人,Lodash的变体

function round(number, precision) {
    var pair = (number + 'e').split('e')
    var value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
    pair = (value + 'e').split('e')
    return +(pair[0] + 'e' + (+pair[1] - precision))
}

用法:

round(0.015, 2) // 0.02
round(1.005, 2) // 1.01

如果您的项目使用jQuery或Lodash,您也可以在库中找到适当的舍入方法。

自从ES6以来,有一种“正确”的方法(不覆盖静态数据和创建变通方法)可以通过使用toPrecision来实现这一点

变量x=1.49999999999;console.log(x.toPrecision(4));console.log(x.toPrecision(3));console.log(x.toPrecision(2));var y=数学PI;console.log(y.toPrecision(6));console.log(y.toPrecision(5));console.log(y.toPrecision(4));变量z=222.987654console.log(z.toPrecision(6));console.log(z-toPrecision(5));console.log(z-toPrecision(4));

然后你可以解析Float,零将“消失”。

console.log(parseFloat((1.4999).toPrecision(3)));console.log(parseFloat((1.005).toPrecision(3)));console.log(parseFloat((1.0051).toPrecision(3)));

但它并不能解决“1.005舍入问题”,因为它是浮点分数处理过程中的固有问题。

控制台日志(1.005-0.005);

如果您对库开放,可以使用bignumber.js

控制台日志(1.005-0.005);console.log(新BigNumber(1.005).减(0.005));console.log(新BigNumber(1.005).round(4));console.log(新BigNumber(1.005).round(3));console.log(新BigNumber(1.005).round(2));console.log(新BigNumber(1.005).rround(1));<script src=“https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/2.3.0/bignumber.min.js“></script>

我正在构建一个简单的tipCalculator,这里有很多答案似乎使问题过于复杂。所以我发现总结这个问题是真正回答这个问题的最佳方式。

如果要创建舍入的十进制数,首先调用Fixed(要保留的小数位数),然后将其包装在number()中。

最终结果是:

let amountDue = 286.44;
tip = Number((amountDue * 0.2).toFixed(2));
console.log(tip)  // 57.29 instead of 57.288

考虑.toFixed()和.toPrecision():

http://www.javascriptkit.com/javatutors/formatnumber.shtml

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