// 计算通用函数
// 核心工具函数
const _toInteger = (num) => {
const str = num.toString()
const pos = str.indexOf('.')
const len = pos === -1 ? 0 : str.length - pos - 1
const times = Math.pow(10, len)
const integer = parseInt(str.replace('.', ''), 10)
return { integer, times }
}
// 加法
const accAdd = (a, b) => {
const { integer: intA, times: timesA } = _toInteger(a)
const { integer: intB, times: timesB } = _toInteger(b)
const maxTimes = Math.max(timesA, timesB)
return (intA * (maxTimes / timesA) + intB * (maxTimes / timesB)) / maxTimes
}
// 减法
const accSub = (a, b) => {
const { integer: intA, times: timesA } = _toInteger(a)
const { integer: intB, times: timesB } = _toInteger(b)
const maxTimes = Math.max(timesA, timesB)
return (intA * (maxTimes / timesA) - intB * (maxTimes / timesB)) / maxTimes
}
// 乘法
const accMul = (a, b) => {
const { integer: intA, times: timesA } = _toInteger(a)
const { integer: intB, times: timesB } = _toInteger(b)
return (intA * intB) / (timesA * timesB)
}
// 除法
const accDiv = (a, b) => {
const { integer: intA, times: timesA } = _toInteger(a)
const { integer: intB, times: timesB } = _toInteger(b)
return (intA / intB) * (timesB / timesA)
}
export {
accAdd,
accSub,
accMul,
accDiv
}
08-19
610
