• 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)

    ---

  • 相关阅读:
    饱和色
    Server.MapPath()相关
    Oracle修改表结构
    远程关机
    使用sqlplus创建表空间
    自写Js+CSS轮显效果
    右下角随机显示的CSS+JS图片广告
    JavaScript实现鼠标放上动画加载大图的代码
    CSS实现自适应的图片背景边框代码
    JavaScript弹性透明的图片放大代码
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12216953.html
Copyright © 2020-2023  润新知