首先 Math类定义在java.lang包下,所以我们使用的时候,不需要引人,直接使用即可。
要想知道round方法是怎么实现的查看源码即可。
Math.round方法的实现如下:
public static long round(double a) {
if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5
return (long)floor(a + 0.5d);
else
return 0;
}
分析这个方法,我们就可以知道,round方法是 +0.5 然后向下取整。(floor()地板的意思,即向下取整-取比当前数字小的整数,ceil()是天花板的意思,即向上取整-取比当前数字大的整数)
package com.luzhiming.test_6_12;
import java.util.Random;
/**
* @author strungle E-mail: 645707787@QQ.com
* @version 创建时间:2013-6-12 下午8:08:52
*
*/
public class Page13Number15 {
public static void main(String[] args) {
// 3.5+0.5 = 4 向下取整:4
System.out.println(Math.round(3.5));
// -3.5+0.5 = -3 向下取整:-3
System.out.println(Math.round(-3.5));
// 3.3+0.5 = 3.8 向下取整:3
System.out.println(Math.round(3.3));
// -3.3+0.5 = -2.8向下取整:-3
System.out.println(Math.round(-3.3));
}
}