You are viewing a single comment's thread from:

RE: JavaScript开发笔记

in #starnote9 days ago

在 JavaScript 中整数和浮点数都属于 Number 数据类型, 在计算时总是会发生精度的问题。使用函数解决,或是使用数学库bignumber.js来解决。

bignumber.js

// 加法 =====================
// 0.1 + 0.2 = 0.30000000000000004
// 0.7 + 0.1 = 0.7999999999999999
// 0.2 + 0.4 = 0.6000000000000001
// 2.22 + 0.1 = 2.3200000000000003

//npm i bignumber.js
cnpm install bignumber.js --save

import BigNumber from "bignumber.js"

const BN = BigNumber.clone()
BN.config({DECIMAL_PLACES:3})
加法:.plus
减法:.minus
乘法:.times
普通除法运算: .div
小数位 .toFixed

转换为js 基础数值类型 .toNumber() ⇒ number
x = new BigNumber(456.789)
x.toNumber() 

0.1 + 0.2                       // 0.30000000000000004
x = new BigNumber(0.1)
y = x.plus(0.2)                 // '0.3'
BigNumber(0.7).plus(x).plus(y)  // '1.1'
x.plus('0.1', 8)                // '0.225'