程序就是一个数学的处理过程,所以在Java语言本身也提供有相应的数字处理的类库支持。
Math类
Math类的主要功能是进行数学计算的操作类,提供有基础的计算公式,这个类的构造方法被私有化了,而且该类之中提供的所有方法都是static型的方法,即:这些方法都可以通过类名称直接调用。
package cn.mldn.demo;
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
System.out.println(Math.abs(-10.1)); // 10.1
System.out.println(Math.max(10.2, 20.3)); // 获取最大值
System.out.println(Math.log(5)); // 1.6094379124341003
System.out.println(Math.round(15.1)); // 15
System.out.println(Math.round(-15.5)); // -15
System.out.println(Math.round(-15.51)); // -16
System.out.println(Math.pow(10.2,20.2)); // 2.364413713591828E20
}
}
虽然在Math类里面提供有四舍五入的处理方法,但是这个四舍五入在进行处理的时候是直接将小数点后的所有位进位处理了,这样肯定不方便,那么现在最方便的做法是可以实现指定位数的保留。
范例:自定义的四舍五入功能
package cn.mldn.demo;
class MathUtil {
private MathUtil() {}
/**
* 实现数据的四舍五入操作
* @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 JavaAPIDemo {
public static void main(String[] args) throws Exception {
System.out.println(MathUtil.round(19.86273, 2));
}
}
Math类里面提供的基本上都是基础的数学公式,需要的时候需要自己重新整合。