js在加减乘除时对浮点型数据有丢失精度问题 比如 0.1+0.2≠0.3;得到的却是0.300...0004,为了防止这个问题可以用一下方法来处理
export default {
/**
* 数字相加
* @param {*} arg1
* @param {*} arg2
* @returns
*/
accAdd (arg1, arg2) {
return this.changeNum(arg1, arg2)
},
/**
* 数字相减
* @param {*} arg1
* @param {*} arg2
* @returns
*/
accSub (arg1, arg2) {
return this.changeNum(arg1, arg2, false)
},
/**
* 数字相乘
* @param {*} arg1
* @param {*} arg2
* @returns
*/
accMul (arg1, arg2) {
let m = 0
m = this.accAdd(m, this.getDecimalLength(arg1))
m = this.accAdd(m, this.getDecimalLength(arg2))
return (this.getNum(arg1) * this.getNum(arg2)) / Math.pow(10, m)
},
/**
* 数字相除
* @param {*} arg1
* @param {*} arg2
* @returns
*/
accDiv (arg1, arg2) {
let t1, t2
t1 = this.getDecimalLength(arg1)
t2 = this.getDecimalLength(arg2)
if (t1 - t2 > 0) {
return this.getNum(arg1) / this.getNum(arg2) / Math.pow(10, t1 - t2)
} else {
return (this.getNum(arg1) / this.getNum(arg2)) * Math.pow(10, t2 - t1)
}
},
changeNum (arg1 = '', arg2 = '', isAdd = true) {
const that = this
function changeInteger (arg, r, maxR) {
if (r !== maxR) {
let addZero = ''
for (let i = 0; i < maxR - r; i++) {
addZero += '0'
}
arg = Number(arg.toString().replace('.', '') + addZero)
} else {
arg = that.getNum(arg)
}
return arg
}
let r1, r2, maxR, m
r1 = this.getDecimalLength(arg1)
r2 = this.getDecimalLength(arg2)
maxR = Math.max(r1, r2)
arg1 = changeInteger(arg1, r1, maxR)
arg2 = changeInteger(arg2, r2, maxR)
m = Math.pow(10, maxR)
if (isAdd) {
return (arg1 + arg2) / m
} else {
return (arg1 - arg2) / m
}
},
getDecimalLength (arg = '') {
try {
return arg.toString().split('.')[1].length
} catch (e) {
return 0
}
},
getNum (arg = '') {
return Number(arg.toString().replace('.', ''))
}
}