Math的一些常用的数学运算(包括取整、保留几位小数等)

1.求两个数中的最大值:Math.max()

public static int max(int a, int b) 
public static long max(long a, long b)
public static float max(float a, float b) 
public static double max(double a, double b) 
2.求两个数中的最小值:Math.min()

public static int min(int a, int b) 
public static long min(long a, long b)
public static float min(float a, float b) 
public static double min(double a, double b) 
3.计算一个数的绝对值:Math.abs()

public static int abs(int a) 
public static long abs(long a)
public static float abs(float a) 
public static double abs(double a) 
4.求a的b次方:Math.pow()

public static double pow(double a, double b) 

注意,返回类型是double

与之容易混淆的是a<<b,表示的是a*(2的b次方)。

5.四舍五入取整:Math.round()

public static int round(float a) 
public static long round(double a)
注意, float型取整后是int型,而double取整后是long型

6.保留n位小数:自己封装方法,策略是先乘以10的n次方,取整后转化为浮点数,再除以10的n次方

public double SplitAndRound(double a, int n) {
	a = a * Math.pow(10, n);
	return (Math.round(a)) / (Math.pow(10, n));
}
上面这个自己封装的方法就可以把一个double型小数四舍五入保留n位小数。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值