美文网首页
准确的JS浮点四则运算方法

准确的JS浮点四则运算方法

作者: microkof | 来源:发表于2020-10-06 20:06 被阅读0次

    原则就一条:永远只让整数进行运算。

    /**
     * @param a
     * @param b
     */
    
    const add = (a, b) => {
      let c = 0,
        d = 0,
        e;
      try {
        c = a.toString().split(".")[1].length;
      } catch (z) {}
      try {
        d = b.toString().split(".")[1].length;
      } catch (z) {}
      e = Math.pow(10, Math.max(c, d));
      return (mul(a, e) + mul(b, e)) / e;
    }
    
    const sub = (a, b) => {
      let c = 0,
        d = 0,
        e;
      try {
        c = a.toString().split(".")[1].length;
      } catch (z) {}
      try {
        d = b.toString().split(".")[1].length;
      } catch (z) {}
      e = Math.pow(10, Math.max(c, d));
      return (mul(a, e) - mul(b, e)) / e;
    }
    
    const mul = (a, b) => {
      let c = 0,
        d = a.toString(),
        e = b.toString();
      try {
        c += d.split(".")[1].length;
      } catch (z) {}
      try {
        c += e.split(".")[1].length;
      } catch (z) {}
      return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    }
    
    const div = (a, b) => {
      let c, d, e = 0, f = 0;
      try {
        e = a.toString().split(".")[1].length;
      } catch (z) {}
      try {
        f = b.toString().split(".")[1].length;
      } catch (z) {}
      c = Number(a.toString().replace(".", ""));
      d = Number(b.toString().replace(".", ""));
      return mul(c / d, Math.pow(10, f - e));
    }
    
    export default {add, sub, mul, div};
    

    相关文章

      网友评论

          本文标题:准确的JS浮点四则运算方法

          本文链接:https://www.haomeiwen.com/subject/mjatpktx.html