js精度丢失的问题,利用lodash函数库重新封装

发布时间 2023-11-30 13:33:44作者: 赵辉Coder
function roundAndPad(num, decimalPlaces) {
    var rounded = _.round(num, decimalPlaces);  // 使用Lodash的_.round函数四舍五入
    var str = rounded.toString();
    var decimalIndex = str.indexOf('.');
    console.log("str:",str);
    console.log(".的位置:",decimalIndex);
    if (decimalIndex === -1) {
        // 如果没有小数点,添加小数点和足够的0
        str += '.' + '0'.repeat(decimalPlaces);
    } else {
        // 如果有小数点,添加足够的0
        var actualDecimalPlaces = str.length - decimalIndex - 1;//目前小数的位数
        console.log("目前小数的位数:",actualDecimalPlaces);
        str += '0'.repeat(decimalPlaces - actualDecimalPlaces);//添加要保留的位数-目前小数的位数
    }
    return str;
}

console.log(roundAndPad(158.9872, 2))