js精度丢失的问题,利用lodash函数库重新封装,解决 toFixed() 四舍五入失效

291 阅读1分钟
function roundAndPad(num, decimalPlaces) {
    // 检查输入
    if (num === '' || num === null || num === undefined || isNaN(num)) {
        console.log('Invalid input');
        return '-';
    }

    // 检查是否指定了小数位数
    if (decimalPlaces === undefined) {
        return num.toString();
    }

    let rounded = _.round(num, decimalPlaces);  // 使用Lodash的_.round函数四舍五入
    let str = rounded.toString();
    let decimalIndex = str.indexOf('.');

    // 如果没有小数点,添加小数点和足够的0
    if (decimalIndex === -1 && decimalPlaces > 0) {
        str += '.' + '0'.repeat(decimalPlaces);
    } else if (decimalIndex !== -1) {
        // 如果有小数点,添加足够的0
        let actualDecimalPlaces = str.length - decimalIndex - 1;
        str += '0'.repeat(Math.max(0, decimalPlaces - actualDecimalPlaces));
    }
    return str;
}

console.log(roundAndPad(158.9872, 2));  // 输出 "158.99"