zoukankan      html  css  js  c++  java
  • javascript乘除算法解决浮点精度

    参考https://www.cnblogs.com/tongshuangxiong/p/11200899.html

    mathDivide = (arg1, arg2, precision) => {
        if (precision === undefined) precision = 4
        let t1 = 0, t2 = 0, r1, r2;
        try { t1 = arg1.toString().split(".")[1].length } catch (e) { }   //--小数点后的长度
        try { t2 = arg2.toString().split(".")[1].length } catch (e) { }  //--小数点后的长度
        // with (Math) {
        r1 = Number(arg1.toString().replace(".", ""))  //--去除小数点变整数
        r2 = Number(arg2.toString().replace(".", ""))  //--去除小数点变整数
        return ((r1 / r2) * Math.pow(10, t2 - t1)).toFixed(precision);   //---整数相除 在乘上10的平方  小数点的长度
        // }
    }
    
    mathMultiply = (arg1, arg2, precision) => {
        if (precision === undefined) precision = 4
        let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try { m += s1.split(".")[1].length } catch (e) { }
        try { m += s2.split(".")[1].length } catch (e) { }
        return (Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)).toFixed(precision)
    }

    注意:上面使用toFixed()控制结果的小数点位数,返回结果是string类型

    let a = 1/3
    console.log(a)
    console.log(typeof a)
    
    a = a.toFixed(2)
    console.log(a)
    console.log(typeof a)

    ---

  • 相关阅读:
    基于OpenSSL自建CA和颁发SSL证书
    SSL与TLS的区别以及介绍
    Ubuntu中Nginx的安装与配置
    Openssl源代码整理学习---含P7/P10/P12说明
    动态加载js文件
    常用方法
    对reducers 理解
    小复习(3)
    如何使移动web页面禁止横屏?
    九个Console命令,让 JS 调试更简单
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12216953.html
Copyright © 2011-2022 走看看