Math.floor函数讲解
floor原意:地板。Math.floor函数是求一个浮点数的地板,就是求一个最接近它的整数,它的值小于或等于这个浮点数。看下面的例子:
代码 | 结果 |
---|---|
Math.floor(-1.1) | -2.0 |
Math.floor(-1.5) | -2.0 |
Math.floor(-1.6) | -2.0 |
Math.floor(0.1) | 0 |
Math.floor(0.5) | 0 |
Math.floor(0.6) | 0 |
Math.ceil函数讲解
ceil愿意:天花板。Math.ceil函数执行的是向上取整计算,它返回的是大于或等于函数参数,并且与之最接近的整数。看下面的例子:
代码 | 结果 |
---|---|
Math.floor(-1.1) | -1.0 |
Math.floor(-1.5) | -1.0 |
Math.floor(-1.6) | -1.0 |
Math.floor(0.1) | 1 |
Math.floor(0.5) | 1 |
Math.floor(0.6) | 1 |
Math.rint函数讲解
Math.rint函数返回最接近参数的整数,如果有2个数同样接近,则返回偶数的那个。
代码 | 结果 |
---|---|
Math.floor(-1.1) | -1.0 |
Math.floor(-1.5) | -2.0 |
Math.floor(-1.6) | -2.0 |
Math.floor(0.1) | 0 |
Math.floor(0.5) | 0 |
Math.floor(0.6) | 1 |
Math.round函数讲解
round方法,它表示”四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整
代码 | 结果 |
---|---|
Math.floor(-1.1) | -1.0 |
Math.floor(-1.5) | -1.0 |
Math.floor(-1.6) | -2.0 |
Math.floor(0.1) | 0 |
Math.floor(0.5) | 1 |
Math.floor(0.6) | 1 |