-- Start
Java 的 Math 和 StrictMath 类提供了一些关于数学运算的静态方法. Math 类中的方法运行速度更快而 StrictMath 类中的方法更为精确.
Math 和 StrictMath 类提供了以下四个方法来进行四舍五入运算.
ceil // 天花板
round // 四舍五入, 返回整数
rint // 四舍五入, 返回浮点数
floor // 地板
来看下面代码的结果, 你就知道它们的意思了.
public static void main(String[] args) {
System.out.println("ceil testing");
System.out.println("1.4 --ceil--> " + Math.ceil(1.4));
System.out.println("1.5 --ceil--> " + Math.ceil(1.5));
System.out.println("-1.4 --ceil--> " + Math.ceil(-1.4));
System.out.println("-1.5 --ceil--> " + Math.ceil(-1.5));
System.out.println();
System.out.println("round testing");
System.out.println("1.4 --round--> " + Math.round(1.4));
System.out.println("1.5 --round--> " + Math.round(1.5));
System.out.println("-1.4 --round--> " + Math.round(-1.4));
System.out.println("-1.5 --round--> " + Math.round(-1.5));
System.out.println();
System.out.println("rint testing");
System.out.println("1.4 --rint--> " + Math.rint(1.4));
System.out.println("1.5 --rint--> " + Math.rint(1.5));
System.out.println("-1.4 --rint--> " + Math.rint(-1.4));
System.out.println("-1.5 --rint--> " + Math.rint(-1.5));
System.out.println();
System.out.println("floor testing");
System.out.println("1.4 --floor--> " + Math.floor(1.4));
System.out.println("1.5 --floor--> " + Math.floor(1.5));
System.out.println("-1.4 --floor--> " + Math.floor(-1.4));
System.out.println("-1.5 --floor--> " + Math.floor(-1.5));
}
结果
ceil testing
1.4 --ceil--> 2.0
1.5 --ceil--> 2.0
-1.4 --ceil--> -1.0
-1.5 --ceil--> -1.0
round testing
1.4 --round--> 1
1.5 --round--> 2
-1.4 --round--> -1
-1.5 --round--> -1
rint testing
1.4 --rint--> 1.0
1.5 --rint--> 2.0
-1.4 --rint--> -1.0
-1.5 --rint--> -2.0
floor testing
1.4 --floor--> 1.0
1.5 --floor--> 1.0
-1.4 --floor--> -2.0
-1.5 --floor--> -2.0
---更多参见:Java 精萃
-- 声 明:转载请注明出处
-- Last Updated on 2012-04-25
-- Written by ShangBo on 2012-04-25
-- End