Web前端小白的全栈之路JavaScript

数据精度问题(浮点数问题)-JavaScript函数封装

2023-07-18  本文已影响0人  MaCong

点击JavaScript查看更多...

精度问题
const dispatchPrecisionAdd = (arg1, arg2) =>{
    let flag_1, flag_2, flag;
    try {
        flag_1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        flag_1 = 0;
    }
    try {
        flag_2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        flag_2 = 0;
    }
    flag = Math.pow(10, Math.max(flag_1, flag_2));
    return (dispatchPrecisionMul(arg1, flag) + dispatchPrecisionMul(arg2, flag)) / flag; // 调用乘法封装
}
const dispatchPrecisionSub = (arg1, arg2)=>{
    let flag_1, flag_2, flag_m, flag_n;
    try {
        flag_1 = arg1.toString.split(".")[1].length;
    } catch (e) {
        flag_1 = 0;
    }
    try {
        flag_2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        flag_2 = 0;
    }
    flag_m = Math.pow(10, Math.max(flag_1, flag_2));
    flag_n = (flag_1 >= flag_2) ? flag_1 : flag_2;
    return ((arg1 * flag_m - arg2 * flag_m) / flag_m).toFixed(flag_n);
}
const dispatchPrecisionMul = (arg1, arg2) =>{
    let flag = 0,flag_1 = arg1.toString(),flag_2 = arg2.toString();
    try {
        flag += flag_1.split(".")[1].length;
    } catch (e) {
    }
    try {
        flag += flag_2.split(".")[1].length;
    } catch (e) { 
    }
    return Number(flag_1.replace(".", "")) * Number(flag_2.replace(".", "")) / Math.pow(10, flag);
}
const dispatchPrecisionDiv = (arg1, arg2)=>{
    let flag = 0, flag_t = 0, flag_1, flag_2;
    try {
        flag = arg1.toString().split(".")[1].length;
    } catch (e) { 
    }
    try {
        flag_t = arg2.toString().split(".")[1].length;
    } catch (e) { 
    }
    flag_1 = Number(arg1.toString().replace(".", ""));
    flag_2 = Number(arg2.toString().replace(".", ""));
    return (flag_1 / flag_2) * Math.pow(10, flag_t - flag);
}

封装

数据精度问题
用法:handlePrecision(0.1,0.2,'add/sub/mul/div')

// 处理精度问题
const handlePrecision = (arg1, agr2, type = 'add') => {
    // 开始循环校验
    switch (type) {
        case 'add': //加法
            return utils.dispatchPrecisionAdd(arg1, agr2)
        case 'sub': //减法
            return utils.dispatchPrecisionSub(arg1, agr2)
        case 'mul': //乘法
            return utils.dispatchPrecisionMul(arg1, agr2)
        case 'div': //除法
            return utils.dispatchPrecisionDiv(arg1, agr2)
    }
}

更多方法尽在专题JavaScript

上一篇下一篇

猜你喜欢

热点阅读