mcya / JavaScriptExperience

👮 JavaScript Experience for web(JavaScript归类:简单入门+数组+经典循环+字符串+函数+Date日期+简单对象+BOM+DOM) +[ Issues(js实用技巧)]
29 stars 8 forks source link

解决js 浮点数相乘精确度问题 #77

Open mcya opened 5 years ago

mcya commented 5 years ago

解决js 浮点数相乘精确度问题

var array = [0.97, 0.99, 0.99], val=1, vals=1;
for (var i = 0; i < array.length; i++) {
    val *= array[i];
    vals = accMul(array[i], vals)
}
console.log(val, vals)
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)
}