安装
npm install --save decimal.js
封装
import { Decimal } from 'decimal.js'
// 加
export function add (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.plus(yy).toNumber()
}
// 减
export function reduce (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.minus(yy).toNumber()
}
// 乘
export function ride (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.mul(yy).toNumber()
}
// 除
export function except (x, y) {
if (!x) {
x = 0
}
if (!y) {
y = 0
}
const xx = new Decimal(x)
const yy = new Decimal(y)
return xx.div(yy).toNumber()
}
使用
import { add, reduce, ride, except } from '@/decimal/decimal'
console.log(0.1 + 0.2)
console.log(add(0.1, 0.2))


本文介绍了一个使用decimal.js库封装的精确数学运算模块,包括加、减、乘、除等基本运算,并提供了安装和使用的示例代码。
6357

被折叠的 条评论
为什么被折叠?



