阿里Java学习路线:阶段 1:Java语言基础-Java语言高级特性:第8章:数字操作类:课时33:Math数学计算类

程序就是一个数学的处理过程,所以在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类里面提供的基本上都是基础的数学公式,需要的时候需要自己重新整合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值