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
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    WCF Server Console
    Restart IIS With Powershell
    RestartService (recursively)
    Copy Files
    Stopping and Starting Dependent Services
    多线程同步控制 ManualResetEvent AutoResetEvent MSDN
    DTD 简介
    Using Powershell to Copy Files to Remote Computers
    Starting and Stopping Services (IIS 6.0)
    java中的NAN和INFINITY
  • 原文地址:https://www.cnblogs.com/huangcong/p/9402452.html
Copyright © 2011-2022 走看看