JS数字计算精度问题解决

 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

 

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

20210104加更

 

  function adder(me) {
    var slice = Array.prototype.slice,
      __args = slice.call(arguments);
    return function () {
      var __inargs = slice.call(arguments);
      if( arguments.length == 0 ){
        var me = 0 ;
        for(var i in __args){
          me = Add(me, __args[i]);//这里为了处理精度问题
        }
        return me ;
      }
      else
        return adder.apply(this, __args.concat(__inargs));
    };
  };
  function Add(arg1,arg2){
    var r1,r2,m;
    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))
    return (arg1*m+arg2*m)/m
  }

多个数字相加,柯里化实现adder(x)(c)(a)....()

 

posted @ 2018-06-12 13:46  疾风_剑豪  阅读(1843)  评论(0编辑  收藏  举报