安装
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))