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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

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');
  });
})

其他回答

我为自己编写了以下一组函数。也许这对你也有帮助。

function float_exponent(number) {
    exponent = 1;
    while (number < 1.0) {
        exponent += 1
        number *= 10
    }
    return exponent;
}
function format_float(number, extra_precision) {
    precision = float_exponent(number) + (extra_precision || 0)
    return number.toFixed(precision).split(/\.?0+$/)[0]
}

用法:

format_float(1.01); // 1
format_float(1.06); // 1.1
format_float(0.126); // 0.13
format_float(0.000189); // 0.00019

对于您的情况:

format_float(10, 1); // 10
format_float(9.1, 1); // 9.1
format_float(1.77777, 1); // 1.78

parseFloat(“1.555”).toFixed(2);//返回1.55而不是1.56。

1.55是绝对正确的结果,因为在计算机中不存在1.555的精确表示。如果读数为1.555,则四舍五入至最接近的值=1.55499999999999994(64位浮点)。将这个数字四舍五入到Fixed(2)得到1.55。

如果输入为1.55499999999999,则此处提供的所有其他功能都会给出故障结果。

解决方案:在扫描前加上数字“5”,将数字舍入(更准确地说,从0开始舍入)。仅当数字真的是浮点(有小数点)时才执行此操作。

parseFloat("1.555"+"5").toFixed(2); // Returns 1.56

简单的通用舍入函数如下:

步骤如下:

使用Math.pow(10,位)将数字乘以(10乘以小数位数的幂)。使用Math.Round将结果舍入为整数。将结果除以(10乘以小数位数的幂)Math.pow(10,位)。

例子:

数字为:1.2375四舍五入至小数点后三位

1.2375 * (10^3) ==> 1.2375 * 1000 = 1237.5舍入为整数==>1238将1238除以(10^3)==>1238/1000=1.238

(注:10^3表示数学功率(10,3))。

函数编号RoundDecimal(v,n){return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(1,n)}//-------测试--------console.log(numberRoundDecimal(-0.0246411603862896567,3))//-0.025console.log(numberRoundDecimal(0.9993360575508052,3))//0.999console.log(numberRoundDecimal(1.0020739645577939,3))//1.002console.log(numberRoundDecimal(0.975,0))//1console.log(numberRoundDecimal(0.975,1))//1console.log(numberRoundDecimal(0.975,2))//0.98console.log(numberRoundDecimal(1.005,2))//1.01

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

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

Math.ceil(num * 100)/100;

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

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

// 123.46