js中的Math.round(),ceil(),floor()

138 阅读1分钟
  • ceil:
    向上取舍
    -floor:
    向下取舍
    -round:

实际上,Math.round()方法准确说是“四舍六入”,对0.5要进行判断对待。
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。