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数字计算精度问题解决
原文地址:https://www.cnblogs.com/maomao93/p/9172625.html