zoukankan      html  css  js  c++  java
  • 黄聪:JS数学计算精度修正

    问题描述

    如果我问你,4330.61乘以100等于多少,我猜你肯定跟我说:“肯定是 433061”啊!
    是啊,要我我也是这么回答,来来来我们来看看浏览器怎么说吧,如下图

     
    浏览器告诉我,他就是算不对

    偌!浏览器告诉我,他就是算不对,这要是给客户算钱,客户不就有意见了....
    WHY?计算机计算出来的还不如我自己的心算呢!!!!
    如果你想了解什么原因,您请看=>js浮点数精度问题的前世今生?

    解决办法

    ;(function(){
      function mathService(){
        this.add=function(a,b){
          var c, d, e;
          try {
            c = a.toString().split(".")[1].length;
          } catch (f) {
            c = 0;
          }
          try {
            d = b.toString().split(".")[1].length;
          } catch (f) {
            d = 0;
          }
          return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e;
       }
    
       this.mul=function(a, b) {
          var c = 0,
            d = a.toString(),
            e = b.toString();
          try {
            c += d.split(".")[1].length;
          } catch (f) {}
          try {
            c += e.split(".")[1].length;
          } catch (f) {}
          return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
        }
    
       this.sub=function(a,b){
         var c, d, e;
         try {
           c = a.toString().split(".")[1].length;
         } catch (f) {
           c = 0;
         }
         try {
           d = b.toString().split(".")[1].length;
         } catch (f) {
           d = 0;
         }
         return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e;
       }
    
       this.div=function(a, b) {
         var c, d, e = 0,
           f = 0;
         try {
           e = a.toString().split(".")[1].length;
         } catch (g) {}
         try {
           f = b.toString().split(".")[1].length;
         } catch (g) {}
         return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e));
       }
      }
    
      window.mathService=new mathService()
    
    })(window);
    

    来来来,用起来

     
    image.png

    Ok!写完收工!!!



    作者:小枫学幽默
    链接:https://www.jianshu.com/p/c3374517b976
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    (x^n-1)在实数域上的标准分解
    子数列收敛定理(任何有界数列必有收敛子数列)
    Islamic empire
    Cauchy收敛准则
    Islamic
    用上下极限判定数列的算数平均值的极限
    妞妞打车之最多的硬币
    信仰1056
    棋盘游戏
    取石子的游戏
  • 原文地址:https://www.cnblogs.com/huangcong/p/9402452.html
Copyright © 2011-2022 走看看