Javascript精確計算時的bug

2021-08-17 10:56:50 字數 1512 閱讀 9152

js無法進行精確計算的bug

在做crm,二代審核需求審核詳情頁面時。需要按比例(後端傳類似0.8的小數)把使用者輸入的數字顯示在不同的地方。 

在做dubheinvest = invest * (1 - ratio);運算時發現問題。具體如下: 

示例**: 

console.log( 1 - 0.8 );  //輸出 0.19999999999999996 

console.log( 6 * 0.7 );  //輸出 4.199999999999999 

console.log( 0.1 + 0.2 );  //輸出 0.30000000000000004 

console.log( 0.1 + 0.7 );  //輸出 0.7999999999999999 

console.log( 1.2 / 0.2 );  //輸出 5.999999999999999 

通過上面舉出的例子可以看到,原生的js運算結果不一定準確,會丟失精度。 

解決方案 

解決方案的原理是,將浮點數乘以(擴大)10的n次方倍,把浮點數變為整數後再進行相應的運算,最後將得到的結果除以(縮小)10的n次方倍。 

原理示例: 

將   console.log(1-0.8);  變為 console.log((1 * 10 - 0.8 * 10) / 10); 即可得到正確的值 

根據上述原理,可以封裝一些方法出來解決此類問題。如下所示(math.pow(x, y);表示求x的y次方): 

/* 加 */

function floatadd(a, b) catch (f)

try catch (f)

return e = math.pow(10, math.max(c, d)), (floatmul(a, e) + floatmul(b, e)) / e;

}/* 減 */

function floatsub(a, b) catch (f)

try catch (f)

return e = math.pow(10, math.max(c, d)), (floatmul(a, e) - floatmul(b, e)) / e;

}/* 乘 */

function floatmul(a, b) catch (f) {}

try catch (f) {}

return number(d.replace(".", "")) * number(e.replace(".", "")) / math.pow(10, c);

}/* 除 */

function floatdiv(a, b) catch (g) {}

try catch (g) {}

return c = number(a.tostring().replace(".", "")), d = number(b.tostring().replace(".", "")), floatmul(c / d, math.pow(10, f - e));

}

javascript數值精確計算

the function for decimal s add,subtract,multiplication,division.not get the float result.and add the function to number s prototype,so you can use it ...

javascript 精確加減乘除

最近乙個專案中要使用 js 實現自動計算的功能,本以為只是實現簡單的加 減 乘 除就可以了,於是三下五除二做完了。正當我竊喜 進行一些浮點數運算時,計算結果都是讓我大跌眼鏡啊,那個值讓我哭笑不得,一長串的值,太牛了。我那個納悶啊!不過還好牛人多,給了我一解決方案,嘿嘿。問題基本上解決了,為了表示感覺...

js精確計算

大多數語言在處理浮點數的時候都會遇到精度問題,但是在js裡似乎特別嚴重,來看乙個例子 alert 45.6 13 結果居然是592.800000000001,當然加法之類的也會有這個問題 那這是js的錯誤嗎?當然不是,你的電腦做著正確的二進位制浮點運算,但問題是你輸入的是十進位制的數,電腦以二進位制...