常用类库-----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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值