加减乘除精度计算问题
加法精度
function add(...val) {
let max = 0
let count = 0
for (let i = 0; i < val.length; i++) {
const strVal = val[i].toString()
const index = strVal.indexOf('.')
let num = 0
if (index > -1) {
num = strVal.length - 1 - index
max = num > max ? num : max
}
}
for (let i = 0; i < val.length; i++) {
count += Math.round(val[i] * Math.pow(10, max))//Math.round() 函数返回一个数字四舍五入后最接近的整数。
}
return count / Math.pow(10, max)
}
console.log(add(0.1,0.2))
乘法精度
function accMul(arg1, arg2) {
var m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length
} catch (e) {}
try {
m += s2.split(".")[1].length
} catch (e) {}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
减法精度
function Subtr(arg1,arg2){
var r1,r2,m,n;
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2));
//last modify by deeka
//动态控制精度长度
n=(r1>=r2)?r1:r2;
return ((arg1*m-arg2*m)/m).toFixed(n);
}
console.log(Subtr(0.1,0.2))
除法精度
function exc(val, valTwo = 100) {
const strVal = val.toString()
const strValTwo = valTwo.toString()
const index = strVal.indexOf('.')
const indexTwo = strValTwo.indexOf('.')
const num = [0, 0]
if (index > -1) {
num[0] = strVal.length - 1 - index
}
if (indexTwo > -1) {
num[1] = strValTwo.length - 1 - index
}
return Math.round(val * Math.pow(10, num[0])) / (Math.round((valTwo * Math.pow(10, num[1]))) * Math.pow(10, num[0] - num[1]))
}
版权声明:本文为qq_41898300原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。