18.处理精度问题
leezozz 3/1/2023 笔记
# 前景
在JavaScript中计算数值的过程中,很容易遇到0.1+0.2!=0.3的问题,其原因是数值由十进制转成双精度浮点数的二进制过程中会出现精度丢失导致的。推荐 decimal.js 库来解决此类问题
# 使用
# 加法:
Decimal.add(1, 2); // 3
const x = new Decimal(1);
const result = x.plus(2); // 3
1
2
3
4
2
3
4
# 减法:
Decimal.sub(3, 1); // 2
const x = new Decimal(3);
const result = x.sub(1); // 2
1
2
3
4
2
3
4
# 乘法:
Decimal.mul(3, 2); // 6
const x = new Decimal(3);
const result = x.mul(2); // 6
1
2
3
4
2
3
4
# 除法:
// 使用除法时候要注意 除数(分母)不能为0
Decimal.div(6, 2); // 3
const x = new Decimal(6);
const result = x.div(2); // 3
1
2
3
4
5
2
3
4
5
# 取绝对值:
Decimal.abs(-3); // 3
const x = new Decimal(-3);
const result = x.abs(); // 3
1
2
3
4
2
3
4
import { Decimal } from 'decimal.js'
// 常见问题:0.03 * 100 = 3.5000000000000004
// 处理精度问题
const curVal = new Decimal(value)
// 【 (值 * 100)% 】
const res = curVal.mul(100) + '%'
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8