Java编程--Java基础类库(Ⅱ Math类)
Math类
java.lang.Math是JDK里唯一一个与数学计算有关的程序类。这个类里提供有一些基础的数学函数。
Math类中所有方法都可以通过类名称直接调用,此类中有一个round(a)方法需要特别注意。
一.Math中的字段
字段摘要 | |
static double | E |
static double | PI |
【范例】通过Math类输出PI和E的值。
public class Test {
public static void main(String[] args) {
System.out.println(Math.PI);
System.out.println(Math.E);
}
}
二.Math中的方法
public static long round(double a)
返回最接近参数的 long。结果将舍入为整数:加上 1/2,对结果调用 floor 并将所得结果强制转换为 long 类型。换句话说,结果等于以下表达式的值:
(long)Math.floor(a + 0.5d)
【范例】观察round()方法。
public class Test {
public static void main(String[] args) {
double num = 1234.56789;
System.out.println(Math.round(num)); // 1235
}
}
如果直接使用round()方法处理的话默认的处理原则就是将小数位直接进位。
【范例】继续观察round()的数据处理。
public class Test {
public static void main(String[] args) {
System.out.println(Math.round(14.55)); // 15
System.out.println(Math.round(14.51)); // 15
// 如果负数小数没大于0.5都不进位
System.out.println(Math.round(-14.55)); // -15
System.out.println(Math.round(-14.51)); // -15
}
}
若希望能准确保存小数位进行处理,怎么办?
【范例】最简单的四舍五入操作处理模式。
class MyRound {
/**
* 进行数据的四舍五入操作
*
* @param num:表示原始的操作数据
* @param scale:表示保留的小数位数
* @return:已经正确四舍五入后的数据内容
*/
public static double round(double num, int scale) {
return Math.round(num * Math.pow(10, scale)) / Math.pow(10, scale);
}
}
public class Test {
public static void main(String[] args) {
System.out.println(MyRound.round(1234.5678, 2)); // 1234.57
}
}