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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

我知道有很多答案,但大多数答案在某些特定情况下都有副作用。

没有任何副作用的最简单和最短的解决方案如下:

Number((2.3456789).toFixed(2)) // 2.35

它正确舍入并返回数字而不是字符串

console.log(Number((2.345).toFixed(2)))  // 2.35
console.log(Number((2.344).toFixed(2)))  // 2.34
console.log(Number((2).toFixed(2)))      // 2
console.log(Number((-2).toFixed(2)))     // -2
console.log(Number((-2.345).toFixed(2))) // -2.35

console.log(Number((2.345678).toFixed(3))) // 2.346

其他回答

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

步骤如下:

使用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

有两种方法可以做到这一点。对于像我这样的人,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,您也可以在库中找到适当的舍入方法。

如果使用的是Lodash库,可以使用Lodash的舍入方法,如下所示。

_.round(number, precision)

例如:

_.round(1.7777777, 2) = 1.78

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

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

您应该使用:

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

似乎没有人知道数字EPSILON。

此外,值得注意的是,这并不像某些人所说的那样是JavaScript的怪异之处。

这就是浮点数在计算机中的工作方式。与99%的编程语言一样,JavaScript没有自制的浮点数;它依赖于CPU/FPU。计算机使用二进制,在二进制中,没有像0.1这样的数字,而只是二进制的近似值。为什么?出于同样的原因,1/3不能用十进制写:它的值是0.33333333……无穷大为三。

这里是Number.EPSILON。这个数字是1和双精度浮点数字中存在的下一个数字之间的差值。就是这样:在1和1+number.EPSILON之间没有数字。

编辑:

正如评论中所问的,让我们澄清一件事:添加Number.EPSILON仅当要舍入的值是算术运算的结果时才相关,因为它可以吞下一些浮点误差增量。

当值来自直接来源(例如:文字、用户输入或传感器)时,它不起作用。

编辑(2019):

像@maganap和一些人指出的那样,最好在相乘之前加上Number.EPSILON:

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

编辑(2019年12月):

最近,我使用了一个类似于此的函数来比较epsilon感知的数字:

const ESPILON_RATE = 1 + Number.EPSILON ;
const ESPILON_ZERO = Number.MIN_VALUE ;

function epsilonEquals( a , b ) {
  if ( Number.isNaN( a ) || Number.isNaN( b ) ) {
    return false ;
  }
  if ( a === 0 || b === 0 ) {
    return a <= b + EPSILON_ZERO && b <= a + EPSILON_ZERO ;
  }
  return a <= b * EPSILON_RATE && b <= a * EPSILON_RATE ;
}

我的用例是我多年来开发的断言+数据验证库。

事实上,在代码中,我使用的是ESPILON_RATE=1+4*数字.EPSILON和EPSILON_ZERO=4*数字.MIN_VALUE(四倍于EPSILON),因为我想要一个足够宽松的等式检查器来累积浮点错误。

到目前为止,它看起来很适合我。我希望这会有所帮助。