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)

    ---

  • 相关阅读:
    tableview 与 tableview cell
    swift基础知识
    HttpRequest
    ios界面跳转
    C# TextBox常用方法总结
    C#中string.format用法详解
    数据库填充DataSet,逐行访问
    C#连接SQL SERVER数据库的详细步骤!
    高德地图API INVALID_USER_SCODE问题以及keystore问题
    基础地图Android SDK
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12216953.html
Copyright © 2011-2022 走看看