Math.floor与Math.round,Math.ceil的区别

本文详细解析了三种常用的数学取整函数:Math.round、Math.ceil 和 Math.floor 的工作原理及应用示例。针对不同场景,这三种函数如何处理正数和负数的小数部分,进行向上或向下取整,以及在遇到.5时的特殊处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,这三个函数都是取整。

Math.round可以简单地理解为“四舍六入”,例如:

Math.round(10.45)=10

Math.round(10.65)=11

Math.round(-10.45)=10

Math.round(-10.65)=11

但是当赋值数小数点后第一位为5时,即x.5时,正数整数位+1,负数整数位不+1,例如:

Math.round(-10.5)=10

Math.round(10.5)=11

Math.ceil是赋值数是正数时,则整数位+1,是负数则整数位不+1,例如:

Math.ceil(10.45)=Math.ceil(10.5)=Math.(10.65)=11

Math.ceil(-10.45)=Math.ceil(-10.5)=Math.(-10.65)=-10

Math.floor与Math.ceil相反,赋值数是正数,则整数位不+1,是负数则整数位+1,例如:

Math.floor(10.45)=Math.floor(10.5)=Math.floor(10.65)=10

Math.floor(-10.45)=Math.floor(-10.5)=Math.floor(-10.65)=-11

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值