常用类库-----15.8Math数学计算

java.lang.Math类来帮助开发者进行常规的数学计算处理。
范例:使用Math类进行数学处理

public class JavaAPIDemo349 {
       public static void main(String[] args) {
		System.out.println(Math.abs(-10.2));   //绝对值
		System.out.println(Math.max(20.3, 22.3));    //获取最大值
		System.out.println(Math.log(5));        //对数
		System.out.println(Math.round(15.1));   //四舍五入
		System.out.println(Math.round(-15.5));   //四舍五入
		System.out.println(Math.round(-15.51));   //四舍五入
		System.out.println(Math.pow(10.2, 20.3));    //乘方
	}
}

执行结果

10.2
22.3
1.6094379124341003
15
-15
-16
2.982520838862122E20

四舍五入中的round()方法直接保留整数,很多时候需要保留到小数,则可以采用自定义工具类的形式完成。

范例:自定义四舍五入工具类

/**
 * 主要是进行数学计算,并且提供的全部都是static方法,该类没有提供属性
 */
class MathUtil {
	private MathUtil() {} ;	// 构造方法私有化
	/**
	 * 进行准确位数的四舍五入处理操作
	 * @param num 要进行四舍五入计算的数字
	 * @param scale 保留的小数位
	 * @return 四舍五入处理后的结果
	 */
	public static double round(double num,int scale) {
		return Math.round(num * Math.pow(10.0, scale)) / Math.pow(10.0, scale) ;
	} 
}
public class JavaAPIDemo {
	public static void main(String[] args) throws Exception {
		System.out.println(MathUtil.round(7.45234789023480234890,3));
	}
}

执行结果
7.452

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章