1、插件:decimal.js (安装插件)
用法:eg:num1+num2
var total = new Decimal(num1).add(new Decimal(num2))
2、思路:小数转化成整数,然后在除以放大的倍数
function publicIsInteger(obj) {
return Math.floor(obj) === obj
}
function publicToInteger(floatNum) {
var ret = { times: 1, num: 0 };
if (publicIsInteger(floatNum)) {
ret.num = floatNum;
return ret
}
var strfi = floatNum + '';
var dotPos = strfi.indexOf('.');
var len = strfi.substr(dotPos + 1).length;
var times = Math.pow(10, len);
var intNum = parseInt(floatNum * times + 0.5, 10);
ret.times = times;
ret.num = intNum;
return ret
}
function publicOperation(a, b, op, n) {
var o1 = publicToInteger(a);
var o2 = publicToInteger(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) { // o1 小数位 大于 o2
result = n1 + n2 * (t1 / t2)
} else { // o1 小数位 小于 o2
result = n1 * (t2 / t1) + n2
}
return result / max;
case 'subtract':
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 'multiply':
result = (n1 * n2) / (t1 * t2);
if (n) {
return toFixed(result, n)
} else {
return toFixed(result, 2)
}
return result;
case 'divide':
result = (n1 / n2) * (t2 / t1);
// 如果除数为0,返回/,防止出错
if (b == 0) {
return '/'
} else {
if (n) {
return toFixed(result, n)
} else {
return toFixed(result, 2)
}
}
}
}
// 加减乘除的四个方法
function publicAdd(a, b) {
return publicOperation(a, b, 'add')
}