java.Math 中有这三个方法:floor,round和ceil
其区别如下:
floor 向下取整 即取不大于原值的最大整数(的double).
说整数只是便于理解,其实floor和ceil返回类型是double类型,而round返回类型的long类型
如:
Math.floor(10.1)=10.0; Math.floor(10.6)=10.0 ;
Math.floor(-10.1)=-11.0; Math.floor(-10.6)=-11.0; //-10.1>-11; -10.6>-11
ceil 向上取整 即不小于原值的最小整数(的double).
如:
Math.ceil(10.1)=11.0; Math.ceil(10.6)=11.0;
Math.ceil(-10.1)=-10.0; Math.ceil(-10.6)=-10.0; //-10.1<-10; -10.6<-10
而round的理解比较复杂,我们可以看下源码:
public static long round(double a) {
return (long)floor(a + 0.5d);
}
即原值加上0.5后向下取整,再转long类型.这样记忆你可以很轻易的计算而不会混淆.(注意负数的运算顺序)
Math.round(10.1)=10; Math.round(10.5)=11; Math.round(10.6)=11;
Math.round(-10.1)=-10; Math.round(-10.5)=-10; Math.round(-10.6)=-11;
-10.1+0.5=-9.6,向下取整为Math.floor(-9.6)=-10.0,所以 Math.round(-10.1)=-10
本文详细介绍了 Java 中 Math 类的 floor、round 和 ceil 方法的区别及使用方法。floor 方法用于向下取整,ceil 方法用于向上取整,而 round 方法则是将原值加上 0.5 后进行向下取整并转换为 long 类型。
451

被折叠的 条评论
为什么被折叠?



