首先判断需要计算的数字是否为整数
// 判断一个数字是否为一个整数
export function isInt(num) {num = Number(num);return Math.floor(num) === num
}
将一个浮点数转为整数,返回整数和倍数。如3.14 返回314 100
export function toInt(num) {var ret = { times: 1, num: 0 };if (isInt(num)) {ret.num = num;return ret}var str = num + '';var dotPos = str.indexOf('.');var len = str.substring(dotPos + 1).length;ret.times = Math.pow(10, len);;ret.num = parseInt(num * ret.times + 0.5, 10);return ret
}
实现假发乘除运算,确保不丢失精度 op运算类型1(add,sub,mul,divide)
// 实现假发乘除运算,确保不丢失精度 op运算类型1(add,sub,mul,divide)
export function operation(a, b, op) {a = Number(a);b = Number(b);var o1 = toInt(a);var o2 = toInt(b);var n1 = o1.num;var n2 = o2.num;var t1 = o1.times;var t2 = o2.times;var max = t1 > t2 ? t1 : t2;var result = null;switch (op) {case 'add':if (t1 === t2) {result = n1 + n2} else if (t1 > t2) {result = n1 + n2 * (t1 / t2)} else {result = n1 * (t2 / t1) + n2}return result / max;case 'sub':if (t1 === t2) {result = n1 - n2} else if (t1 > t2) {result = n1 - n2 * (t1 / t2)} else {result = n1 * (t2 / t1) - n2}return result / max;case 'mul':result = (n1 * n2) / (t1 * t2)return resultcase 'divide':result = (n1 / n2) * (t2 / t1)return result}
}
具体使用(比如计算100*1.1)
let num = operation(100, 1.1, 'mul')
扩展 进一法保留n位小数
export function roundUp(num, n = 2) {let factor = Math.pow(10, n);return Math.ceil(num * factor) / factor;}roundUp(operation(100, 1.1, 'mul'))