Java Math、BigInteger、BigDecimal类

版权声明:尊重原创,码字不易,转载需博主同意。 https://blog.csdn.net/qq_34626097/article/details/84900557

Java Math、BigInteger、BigDecimal类

1. java.lang.Math

java.lang.Math 提供了一系列静态方法用于科学计算;其方法的参数和返回值类型一般为double型。
- abs 绝对值
- acos,asin,atan,cos,sin,tan 三角函数
- sqrt 平方根
- pow(double a,doble b) a的b次幂
- log 自然对数
- exp e为底指数
- max(double a,double b)
- min(double a,double b)
- random() 返回0.0到1.0的随机数
- long round(double a) double型数据a转换为long型(四舍五入)
- toDegrees(double angrad) 弧度—>角度
- toRadians(double angdeg) 角度—>弧度

注:凡是数学相关的方法都在Math类中的静态方法中找

2. BigInteger类

Integer类作为int的包装类,能存储的最大整型值为2^31−1,BigInteger类的数字范围较Integer类的数字范围要大得多,可以支持任意精度的整数

- 构造器

BigInteger(String val)
- 常用方法
* public BigInteger abs()
* public BigInteger add(BigInteger val)
* public BigInteger subtract(BigInteger val)
* public BigInteger multiply(BigInteger val)
* public BigInteger divide(BigInteger val)
* public BigInteger remainder(BigInteger val)
* public BigInteger pow(int exponent)
* public BigInteger[] divideAndRemainder(BigInteger val)

3. BigDecimal类

一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中,要求数字精度比较高,故用到java.math.BigDecimal类。BigDecimal类支持任何精度的定点数。

  1. 构造器
    • public BigDecimal(double val)
    • public BigDecimal(String val)
  2. 常用方法
    • public BigDecimal add(BigDecimal augend)
    • public BigDecimal subtract(BigDecimal subtrahend)
    • public BigDecimal multiply(BigDecimal multiplicand)
    • public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)

4. demo

public void testBigInteger(){

	BigInteger bi = new BigInteger("12433241123");
	BigDecimal bd = new BigDecimal("12435.351");
	BigDecimal bd2 = new BigDecimal("11");
	System.out.println(bi);
	//System.out.println(bd.divide(bd2));
	System.out.println(bd.divide(bd2,BigDecimal.ROUND_HALF_UP));
	System.out.println(bd.divide(bd2,15,BigDecimal.ROUND_HALF_UP));

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34626097/article/details/84900557