Math.round(-1.5)

109 阅读1分钟

Math.round()是经常会用到的函数,都知道他的功能是四舍五入。但是我却没有考虑过,参数传负数的情况

定义:

developer.mozilla.org/zh-CN/docs/…

问题:

首先看下下面的几个结果:

Math.round(1.0)

Math.round(1.4)

Math.round(1.5)

Math.round(1.6)

结果分别为1,1,2,2。这没什么好说的。

那么如果传入的参数为负数呢?

Math.round(-1.0)

Math.round(-1.4)

Math.round(-1.5)

Math.round(-1.6)

结果分别为-1,-1,-1,-2。

注意Math.round(-1.5),也就是-1.5“四舍五入”的结果并不是-2,而是-1。这是为什么呢?

原因: