BigInter类和Decimallei类

应用场景

  1. BigInteger适用保存比较大的整型
  2. BigDecimal适用精度更高的浮点型(小数)

BigInteger

当编程中需要处理很大的整数,long不够用时可以使用BigInteger的类解决。

需要对BigInteger进行加减乘除的时候,需要使用对应的方法。

先创建一个需要操作的BigInteger然后进行操作

public class BigInteger_ {
    public static void main(String[] args) {

        // long l = 4545632135555555555555555555555;
        BigInteger bigInteger = new BigInteger("4545632135555555555555555555555");
        System.out.println("原数值=" + bigInteger);
        BigInteger bigInteger1 = new BigInteger("5");
        BigInteger bigInteger2 = bigInteger.add(bigInteger1);   // 加法
        System.out.println("原数值+5=" + bigInteger2);
        BigInteger bigInteger3 = bigInteger.subtract(bigInteger1);   // 减法
        System.out.println("原数值-5=" + bigInteger3);
        BigInteger bigInteger4 = bigInteger.multiply(bigInteger1);
        System.out.println("原数值/5=" +bigInteger4);
        BigInteger bigInteger5 = bigInteger.divide(bigInteger1);
        System.out.println("原数值*5=" +bigInteger5);

    }
}

BigDecimal 

当程序需要一个精度很高(double不够用)的数时使用BigDecimal

对BigDecimal进行加减乘除要使用对应的方法。

创建一个需要操作的BigDecimal后调用对应的方法即可。

其中除法除不尽时会抛出异常

public class BigDecimal_ {
   public static void main(String[] args) {
      BigDecimal bigDecimal = new BigDecimal("1949.10101010010101010100010111110");
      System.out.println(bigDecimal);
      BigDecimal bigDecimal1 = new BigDecimal("1.001");
      System.out.println(bigDecimal.add(bigDecimal1));
      System.out.println(bigDecimal.subtract(bigDecimal1));
      System.out.println(bigDecimal.multiply(bigDecimal1));
      // System.out.println(bigDecimal.divide(bigDecimal1));   // 除不尽的数会抛出异常
      //除不尽小数会保留分子的精度
      System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));
   }
}

 

posted @ 2024-07-05 16:29  Dr丶云幕  阅读(1)  评论(0编辑  收藏  举报