在java中怎么对一个数字取整?

Python021

在java中怎么对一个数字取整?,第1张

在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

有float类型的\x0d\x0a\x0d\x0a向上取整:Math.ceil() //只要有小数都+1\x0d\x0a向下取整:Math.floor() //不取小数\x0d\x0a四舍五入:Math.round() //四舍五入

通过(int)方式进行取整,(int)是强转,强制把其他类型转换成整型。

语法:

int b =(int)浮点型变量

例如:

double a = 1.22

int b=(int)a//强转double为整型。,取整,结果为1