js中Math.floor、Math.ceil、Math.round和parseInt小数取整小结

虽然知道结果都可以返回一个整数,但是四者的区别尤其是关于-0.5的取整情况貌似还是需要注意一下
一、Math.floor(向下取整)

作用:返回小于等于参数的最大整数。

eg:

Math.floor(5.65)  //返回5

Math.floor(2.4)  //返回2

Math.floor(1.5)  //返回2

Math.floor(-1.5)  //返回-2

Math.floor(-5.8)  //返回-6

二、Math.ceil(向上取整)

作用:返回大于等于参数的最小整数

eg:

Math.ceil(5.65)  //返回6

Math.ceil(2.4)  //返回3

Math.ceil(1.5)  //返回2

Math.ceil(-1.5)  //返回-1

Math.ceil(-5.8)  //返回-5

三、Math.round(四舍五入)

作用:四舍五入,返回参数+0.5后,向下取整。(简单来说就是不管正负数,统一加上0.5,再向下取数。向下的意思是往小的方向取,如Math.round(-8.6)先-8.6+0.5=-8.1,再向下取整得到-9)

eg:

Math.round(5.65)  //返回6

Math.round(2.4)   //返回2

Math.round(1.5)  //返回2

Math.round(-1.5)  //返回-1

Math.round(-5.8)  //返回-6

四、parseInt(简单理解为直接舍去小数部分取整)

作用:解析一个字符串,并返回一个整数,这里可以简单理解成返回舍去参数的小数部分后的整数。

eg:

parseInt(5.65)  //返回5

parseInt(2.4)  //返回2

parseInt(1.5)  //返回1

parseInt(-1.5)  //返回-1

parseInt(-5.8)  //返回-5

本文作者:seven&night

本文链接:https://www.cnblogs.com/bisiyuan/p/16981597.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   seven&night  阅读(3083)  评论(1编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 晴天 刘瑞琦
晴天 - 刘瑞琦
00:00 / 00:00
An audio error has occurred.