JS计算加减乘除出现多位小数的解决方法
作者:互联网
function add(arg1, arg2){ let decima1, decima2, differ, m; try { decima1 = arg1.toString().split('.')[1].length } catch(err) { decima1 = 0 } try { decima2 = arg2.toString().split('.')[1].length } catch (err) { decima2 = 0 } differ = Math.abs(decima1 - decima2) m = Math.pow(10, Math.max(decima1, decima2)) if(differ > 0) { let differM = Math.pow(10, differ) if(decima1 > decima2) { arr1= Number(arg1.toString().replace('.', '')) arr2 = Number(arg2.toString().replace('.', '')) * differM } else { arr1 = Number(arg1.toString().replace('.', '')) * differM arr2 = Number(arg2.toString().replace('.', '')) } } else { arr1 = Number(arg1.toString().replace('.','')) arr2 = Number(arg2.toString().replace('.', '')) } return (arg1 + arg2) / m }
获取两个数的小数位decima1、decima2,把最大的小数位当作10的次方 m,将两个数都转化成整数并相加然后除以 m
标签:arg1,arg2,JS,replace,toString,decima1,decima2,加减乘除,小数 来源: https://www.cnblogs.com/xiuxiume/p/15977686.html