1.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.0
Math.floor(0.5): 0.0
Math.floor(0.6): 0.0
Math.floor(1.1): 1.0
Math.floor(11.5): 11.0
Math.floor(15.7): 15.0
Math.floor(-0.5): -0.0
2.Math.ceil
ceil,英文原意:天花板。
Math.ceil 函数执行的是 向上 取接近的整数,它返回的肯定会大于或等于函数参数。
Math.ceil(-1.1): -1.0
Math.ceil(-1.5): -1.0
Math.ceil(-1.6): -1.0
Math.ceil(0.1): 1.0
Math.ceil(0.5): 1.0
Math.ceil(0.6): 1.0
Math.ceil(1.1): 2.0
Math.ceil(1.5): 2.0
Math.ceil(1.6): 2.0
Math.ceil(-0.5): -1.0
3.Math.rint
Math.rint 函数返回最接近参数的整数,如果有2个数同样接近,则会返回偶数的那个。
Math.rint(-1.1): -1.0
Math.rint(-1.5): -2.0
Math.rint(-1.6): -2.0
Math.rint(0.1): 0.0
Math.rint(0.5): 0.0
Math.rint(0.6): 1.0
Math.rint(1.1): 1.0
Math.rint(1.5): 2.0
Math.rint(1.6): 2.0
4.Math.round
round 方法,我们通常会说这个方法表示”四舍五入”,但是当参数为负数时,就不太好理解。
所以,以源码的计算方式来理解会比较准确。
即将原来的数字加上0.5后再向下取整。
源码大意:
Math.round(x) = Math.floor(x + 0.5)
Math.round(-1.1): -1
Math.round(-1.5): -1
Math.round(-1.6): -2
Math.round(0.1): 0
Math.round(0.5): 1
Math.round(0.6): 1
Math.round(1.1): 1
Math.round(1.5): 2
Math.round(1.6): 2
在java中对一个数字取整方法很多
向上取整Math.ceil()
举例:Math.ceil(11.4)=12Math.ceil(-11.6)=-11
2.向下取整Math.floor()
举例:Math.floor(11.7)=11Math.floor(-11.2)=-12
3.四舍五入Math.round()
顾名思义,四舍五入后取整,其算法为Math.round(x+0.5),即原来的数字加上0.5后再想下取整即可。
举例:Math.round(11.5)=12
Math.round(-11.5)=-11