JS數字計算精度問題解決
阿新 • • 發佈:2018-06-12
try sub style 題解 會有 str add col eee
1 add(a, b) {//相加 2 var c, d, e; 3 try { 4 c = a.toString().split(".")[1].length; 5 } catch (f) { 6 c = 0; 7 } 8 try { 9 d = b.toString().split(".")[1].length; 10 } catch (f) { 11 d = 0;12 } 13 return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e; 14 }, 15 sub(a, b) {//相減 16 var c, d, e; 17 try { 18 c = a.toString().split(".")[1].length; 19 } catch (f) { 20 c = 0; 21 } 22 try{ 23 d = b.toString().split(".")[1].length; 24 } catch (f) { 25 d = 0; 26 } 27 return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e; 28 }, 29 mul(a, b) {//主體 30 var c = 0, 31 d = a.toString(), 32 e = b.toString();33 try { 34 c += d.split(".")[1].length; 35 } catch (f) { } 36 try { 37 c += e.split(".")[1].length; 38 } catch (f) { } 39 return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c); 40 }, 41 div(a, b) {//除 42 var c, d, e = 0, 43 f = 0; 44 try { 45 e = a.toString().split(".")[1].length; 46 } catch (g) { } 47 try { 48 f = b.toString().split(".")[1].length; 49 } catch (g) { } 50 return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e)); 51 }
js在數字計算時,因為IEEE 754會有精度丟失,完善一下,需要用到哪個,只要mul和你用到的函數就OK
JS數字計算精度問題解決