zoukankan      html  css  js  c++  java
  • 封装加减乘除函数 解决JS 浮点数计算 Bug

    计算机内部的信息都是由二进制方式表示的,即0和1组成的各种编码,但由于某些浮点数没办法用二进制准确的表示出来,也就带来了一系列精度问题。当然这也不是JS独有的问题。

    例如, 我们在用JS做浮点运算会遇到这样的bug : 

    0.1 + 0.2 = 0.30000000000000004

    7 * 0.8 = 5.6000000000000005

    解决方法 -> 将小数转成整数来运算,之后再转回小数。

     1 function add(a, b) {
     2     var x, y, z;
     3     try {
     4         x = a.toString().split(".")[1].length;
     5     } catch (f) {
     6         x = 0;
     7     }
     8     try {
     9         y = b.toString().split(".")[1].length;
    10     } catch (f) {
    11         y = 0;
    12     }
    13     return z = Math.pow(10, Math.max(x, y)), (mul(a, z) + mul(b, z)) / z;
    14 }
     1 function sub(a, b) {
     2     var x, y, z;
     3     try {
     4         x = a.toString().split(".")[1].length;
     5     } catch (f) {
     6         x = 0;
     7     }
     8     try {
     9         y = b.toString().split(".")[1].length;
    10     } catch (f) {
    11         y = 0;
    12     }
    13     return z = Math.pow(10, Math.max(x, y)), (mul(a, z) - mul(b, z)) / z;
    14 }
     1 function mul(a, b) {
     2     var c = 0,
     3         d = a.toString(),
     4         e = b.toString();
     5     try {
     6         c += d.split(".")[1].length;
     7     } catch (f) {}
     8     try {
     9         c += e.split(".")[1].length;
    10     } catch (f) {}
    11     return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    12 }
     1 function div(a, b) {
     2     var c, d, e = 0,
     3         f = 0;
     4     try {
     5         e = a.toString().split(".")[1].length;
     6     } catch (g) {}
     7     try {
     8         f = b.toString().split(".")[1].length;
     9     } catch (g) {}
    10     return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
    11 }

    用上面的方法进行浮点类型的四则运算就可以放心的玩耍了

  • 相关阅读:
    Windows Store App 主题动画
    Windows Store App 过渡动画
    Windows Store App 控件动画
    Windows Store App 近期访问列表
    Windows Store App 文件选取器
    Windows Store App 访问应用内部文件
    Windows Store App 用户库文件分组
    Windows Store App 获取文件及文件夹列表
    Windows Store App 用户库文件夹操作
    Windows Store App 用户库文件操作
  • 原文地址:https://www.cnblogs.com/spotman/p/10819239.html
Copyright © 2011-2022 走看看