Math.round()方法即为我们常说的“四舍五入”方法,但Math.round()方法准确说是“四舍六入”,5要进行判断对待。
首先看下下面的几个结果:如果传入的参数是正数的话:
console.log(Math.round(1.0) )//1
console.log(Math.round(1.4) )//1
console.log(Math.round(1.5) )//2
console.log(Math.round(1.6) )//2
如果传入的参数是负数的话就会发生怪异行为:
console.log(Math.round(-1.0) )//-1
console.log(Math.round(-1.4) )//-1
console.log(Math.round(-1.5) )//-1
console.log(Math.round(-1.6) )//-2
原理:Math.round()的原理是对传入的参数+0.5之后,再向下取整得到的数就是返回的结果。这里的向下取整是说取比它小的第一个整数或者和它相等的整数。
因此Math.round(-1.5)的结果是-1.5 + 0.5 再向下取整,即-1.0取整,结果是-1.
Math.round(-1.4)的结果是 -1.4 + 0.5 即-0.9 向下取整,结果是-1。
Math.round(1.5)即为 1.5 + 0.5 再向下取整,结果是2。