JS中Math.round()的特殊性

Math.round()方法即为我们常说的“四舍五入”方法,但Math.round()方法准确说是“四舍六入”,5要进行判断对待。

首先看下下面的几个结果:如果传入的参数是正数的话:

    console.log(Math.round(1.0) )//1
    console.log(Math.round(1.4) )//1
    console.log(Math.round(1.5) )//2
    console.log(Math.round(1.6) )//2

如果传入的参数是负数的话就会发生怪异行为:

    console.log(Math.round(-1.0) )//-1
    console.log(Math.round(-1.4) )//-1
    console.log(Math.round(-1.5) )//-1
    console.log(Math.round(-1.6) )//-2


原理: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。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值