js 四舍五入

js的.toFixed(fixed)在chrome中不是真正的四舍五入, 比如:

1.255.toFixed(2)
1.25

1.215.toFixed(2)
1.22

记录一下自己造的轮子:

function roundHalfUp(num, fixed){
    let numStr = num.toString();
    let decimalPlaces = numStr.indexOf('.');
    let fixedIdx = decimalPlaces + fixed;
    if(decimalPlaces <= -1 || numStr.length <= (fixedIdx + 1)){
        return num;
    }
    let result = parseFloat(numStr.slice(0, fixedIdx + 1));
    if(numStr.charAt(fixedIdx + 1) < '5'){
        return result;
    } else {
        return result + Math.pow(10.0, -1*fixed);
    }
}

 测试一下:

roundHalfUp(1.215, 2)
1.22
roundHalfUp(1.214, 2)
1.21
roundHalfUp(1.254, 2)
1.25
roundHalfUp(1.255, 2)
1.26
原文地址:https://www.cnblogs.com/tlz888/p/14776625.html