Javascript 双精度浮点数计算精度问题

我们用JS进行浮点数运算时,比如0.1 + 0.2,经常会得到一个意想不到的结果:

1
2
console.log(0.1 + 0.2) // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3) // false

这个结果是不是很匪夷所思,那么是什么造成这个结果的呢?

原理分析

简单来说,JavaScript 的 Number 遵循 IEEE 754 标准,使用 64 位双精度浮点数表示。部分十进制小数无法用有限位二进制精确表示,存储和运算时的舍入就会产生误差。JavaScript 另有 BigInt 类型,但它只表示整数。

更深度的解析请参考:JavaScript 浮点数陷阱以及解法

事实上,这个问题并不只出现在JS里,其他遵循IEEE 754标准的语言,同样存在此问题。

解决方案

这个问题既然已经存在很长时间了,那么解决方案自然也就有很多了。

官方方案

BigInt 已是 JavaScript 标准的一部分,适合超过 Number.MAX_SAFE_INTEGER 范围的整数运算。它不能表示小数,也不能解决 0.1 + 0.2 的问题;BigInt 和 Number 也不能直接混合进行算术运算。涉及金额、税率等十进制小数时,应按精度要求选择十进制计算库,并优先用字符串传入原始数值,避免输入时就丢失精度。

参考:MDN BigInt。

主动缩小精度范围

利用toPrecision或toFixed主动把溢出造成的细微差异过滤掉。这种方案吧,只适合浮点数,对于整数的溢出,是束手无策的。

转为整数计算

这种方案跟上面的也差不多,只适合小数。对于包含n位小数的number,先乘10的n次方,再进行计算,最后结果再除10的n次方归位

转为字符串再进行计算

这种应该是目前最普遍的解决方案了,大多数成熟计算框架都采用的此方案。优点是完全不受number存储空间的限制,可以胜任更准确更精细的计算,缺点是性能相对较差。

借助第三方计算框架

math.js

Math.js是一个用于JavaScript和Node.js的扩展数学库。它具有支持符号计算的灵活表达式解析器,大量内置函数和常量,并提供了集成的解决方案来处理不同的数据类型,例如数字,大数,复数,分数,单位和矩阵。强大且易于使用。

官网:https://mathjs.org/
中文资料站:https://www.mathjs.cn/
GitHub:https://github.com/josdejong/mathjs

例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// 函数和常量
math.round(math.e, 3) // 2.718
math.atan2(3, -3) / math.pi // 0.75
math.log(10000, 10) // 4
math.sqrt(-4) // 2i
math.derivative('x^2 + x', 'x') // 2*x+1
math.pow([[-1, 2], [3, 1]], 2)
// [[7, 0], [0, 7]]
// 表达式
math.evaluate('1.2 * (2 + 4.5)') // 7.8
math.evaluate('12.7 cm to inch') // 5 inch
math.evaluate('sin(45 deg) ^ 2') // 0.5
math.evaluate('9 / 3 + 2i') // 3 + 2i
math.evaluate('det([-1, 2; 3, 1])') // -7
// 链接
math.chain(3)
.add(4)
.multiply(2)
.done() // 14

decimal.js

此库 与 bignumber.js相似,但是注意此库的精度是以 有效数字 来规定的,而不是小数点的位置. 此库中所有的运算都是四舍五入到 对应的精度(类似于python中的 decimal 模块),而不是仅仅只是除法运算四舍五入

官网:http://mikemcl.github.io/decimal.js/
GitHub:https://github.com/MikeMcl/decimal.js/

例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

x = new Decimal(9) // '9'
y = new Decimal(x) // '9'

new Decimal('5032485723458348569331745.33434346346912144534543')
new Decimal('4.321e+4') // '43210'
new Decimal('-735.0918e-430') // '-7.350918e-428'
new Decimal('5.6700000') // '5.67'
new Decimal(Infinity) // 'Infinity'
new Decimal(NaN) // 'NaN'
new Decimal('.5') // '0.5'
new Decimal('-0b10110100.1') // '-180.5'
new Decimal('0xff.8') // '255.5'

new Decimal(0.046875) // '0.046875'
new Decimal('0.046875000000') // '0.046875'

new Decimal(4.6875e-2) // '0.046875'
new Decimal('468.75e-4') // '0.046875'

new Decimal('0b0.000011') // '0.046875'
new Decimal('0o0.03') // '0.046875'
new Decimal('0x0.0c') // '0.046875'

new Decimal('0b1.1p-5') // '0.046875'
new Decimal('0o1.4p-5') // '0.046875'
new Decimal('0x1.8p-5') // '0.046875'

bignumber.js

bignumber.js是一款用于任意精度十进制和非十进制算术的JavaScript库

官网:https://mikemcl.github.io/bignumber.js/
GitHub:https://github.com/MikeMcl/bignumber.js

例

1
2
3
4
5

const BigNumber = require('bignumber.js');
const result = new BigNumber('0.1').plus('0.2');
console.log(result.toString()); // '0.3'

big.js

‎Big.js是JavaScript的”bignumber”实现。这意味着您可以使用它以任何精度存储任何量级的数字,并在 JavaScript 中对它们执行数学运算。‎

官网:http://mikemcl.github.io/big.js/
Github:https://github.com/MikeMcl/big.js/

1
2
3
4
5
6
7
8
9
10

x = new Big(9) // '9'
y = new Big(x) // '9'
new Big('5032485723458348569331745.33434346346912144534543')
new Big('4.321e+4') // '43210'
new Big('-735.0918e-430') // '-7.350918e-428'
Big(435.345) // '435.345'
new Big() // 'Error: [big.js] Invalid value'
Big() // No error, and a new Big constructor is returned

参考文章

深度剖析0.1 +0.2===0.30000000000000004的原因
如何解决0.1 +0.2===0.30000000000000004类问题
两分钟解惑 JS 小数计算精度问题
JavaScript 浮点数陷阱以及解法

本文永久链接: https://www.mulianju.com/BigNumber/