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)

---

原文地址:https://www.cnblogs.com/xy-ouyang/p/12216953.html