Math.ceil、Math.floor、Math.round之间用法和区别

Math.ceil、Math.floor、Math.round之间用法和区别


 一、描述

Math.ceil():向上取整,即它总是将数值向上舍入为最接近的整数;
Math.floor():向下取整,即它总是将数值向下舍入为最接近的整数;
Math.round():四舍五入,即它总是将数值四舍五入为最接近的整数。

二、用法

ceil():舍去小数部分,整数部分进1位。
如:

Math.ceil(6.9)——返回值为:7

Math.ceil(6.5)——返回值为:7

Math.ceil(6.1)——返回值为:7

Math.ceil(6.0)——返回值为:6  (★注意此处不应进位)

floor():舍去小数部分,仅保留整数。

如:

Math.floor(6.9)——返回值为:6

Math.floor(6.5)——返回值为:6

Math.floor(6.1)——返回值为:6

Math.floor(6.0)——返回值为:6  

round():小数部分进行四舍五入
如:

Math.round(6.9)——返回值为:7

Math.round(6.5)——返回值为:7

Math.round(6.4)——返回值为:6

Math.round(6.1)——返回值为:6

Math.round(6.0)——返回值为:6 

三、总结

  6 < x < 7之间的数值,Math.ceil():始终返回7,因为它执行的是向上取整;Math.floor():始终返回6,因为它执行的是向下取整;Math.round():当6 < x < 6.5时,始终返回6。当6.5 ≤ x <7时,始终返回7。

posted @ 2020-09-04 21:54  琴时  阅读(1171)  评论(0编辑  收藏  举报