JavaScript Math.round()四舍五入误差问题

Math.round(1.3) //1
Math.round(1.6) //2

然后在对-0.5或者-2.5进行round的时候却出现了意料之外的结果:

Math.round(-0.5) //0
Math.round(-2.5) //-2

究其原因,主要是因为Math.round的实现原理造成的:
Math.round(n)首先对n进行+0.5操作,然后对结果进行Math.floor()运算。于是Math.round(-2.5)的运算过程可以看做:

function mathround(n) { //-2.5
    var nn = n + 0.5 //-2
    return Math.floor(nn) //-2
}
mathround(-2.5)

你可能感兴趣的:(JavaScript Math.round()四舍五入误差问题)