java中BigInteger类和BigDecimal类

目录

  • BigInteger类
    • 构造方法
    • 用构造方法创建对象
    • BigInteger的四则运算(只能是整数)
      • 加法(add方法)
      • 减法(subtract方法)
      • 乘法(multiply方法)
      • 除法(divide方法)
  • BigDecimal类
    • 构造方法
    • 用构造方法创建对象
    • BigDecimal的四则运算
      • 加法(add方法)
      • 减法(subtract方法)
      • 乘法(multiply方法)
      • 乘法(divide方法)

BigInteger类

BigInteger类位于:java.math.BigInteger包
BigInteger类表示超大整数,而且支持任意精度的四则运算.
**应用场景:**当int和long都不能满足需求时.

构造方法

public BigInteger(String val) {
        this(val, 10);
    }

用构造方法创建对象

BigInteger a = new BigInteger("字符串数字");

BigInteger的四则运算(只能是整数)

加法(add方法)

数字1.add(数字2);

		BigInteger a = new BigInteger("1");
        BigInteger b = new BigInteger("2");
        BigInteger add = a.add(b);
        System.out.println(add);//3

减法(subtract方法)

数字1.subtract(数字2);

		BigInteger a = new BigInteger("5");
        BigInteger b = new BigInteger("2");
        BigInteger subtract = a.subtract(b);
        System.out.println(subtract);//3

乘法(multiply方法)

数字1.multiply(数字2);

		BigInteger a = new BigInteger("5");
        BigInteger b = new BigInteger("2");
        BigInteger multiply = a.multiply(b);
        System.out.println(multiply);//10

除法(divide方法)

数字1.divide(数字2);

		BigInteger a = new BigInteger("5");
        BigInteger b = new BigInteger("2");
        BigInteger divide = a.divide(b);
        System.out.println(divide);//2

注意:
进行除法运算时会只去整数部分.

BigDecimal类

解决了浮点数在计算的时候精度问题.
如:

System.out.println(1.0-0.32);
//0.6799999999999999

BigDecimal类是为了解决浮点数运算精度问题,它表示任意精度超大浮点数.
如果在日常开发时,如果有浮点数的运算,禁止使用float或double,由于浮点数的存储机制可能导致运算有误差.

构造方法

public BigDecimal(String val) {
        this(val.toCharArray(), 0, val.length());
    }

用构造方法创建对象

 BigDecimal bd = new BigDecimal("小数字符串");

BigDecimal的四则运算

加法(add方法)

浮点数1.add(浮点数2);

		BigDecimal bd1 = new BigDecimal("1.23");
        BigDecimal bd2 = new BigDecimal("1.23");
        BigDecimal add = bd1.add(bd2);
        System.out.println(add);//2.46

减法(subtract方法)

浮点数1.subtract(浮点数2);

		BigDecimal bd1 = new BigDecimal("2.23");
        BigDecimal bd2 = new BigDecimal("1.23");
        BigDecimal subtract = bd1.subtract(bd2);
        System.out.println(subtract);//1.00

乘法(multiply方法)

浮点数1.multiply(浮点数2);

		BigDecimal bd1 = new BigDecimal("2.23");
        BigDecimal bd2 = new BigDecimal("2.2");
        BigDecimal multiply = bd1.multiply(bd2);
        System.out.println(multiply);//4.906

乘法(divide方法)

浮点数1.divide(浮点数2);

		BigDecimal bd1 = new BigDecimal("4.906");
        BigDecimal bd2 = new BigDecimal("2.2");
        BigDecimal divide = bd1.divide(bd2);
        System.out.println(divide);//2.23

你可能感兴趣的:(java,开发语言)