很多人在用JS实现四舍五入的时候直接用tofixed 或 math.round 等方法都是不行的。要不会出现五不入,要不会出现四不舍的情况。
下面提供一个JS实现四舍五入的解决方法:
函数:
function round(num, decimal) {
if (isNaN(num)) {
return 0;
}
const num1 = Math.pow(10, decimal + 1);
const num2 = Math.pow(10, decimal);
const res = Math.round(num * num1 / 10) / num2;
return res.toFiexed(decimal);
}
console.log(round(23.235,2)) ==> 23.24
console.log(round(23.234,2)) ==> 23.23