BigInteger和BigDecimal

BigInteger和BigDecimal

  1. Biglnteger适合保存比较大的整型
  2. BiaDecimal活合保存精度更高的浮点型小数)

一、BigInteger的常用方法

  1. add
  2. subtract
  3. multiply
  4. divide
package com.hspedu.bignum_;

import java.math.BigInteger;

/**
 * @author DL5O
 * @version 1.0
 */
public class BigInteger_ {
    public static void main(String[] args) {
        //当编程中,需要处理很大的数,long就不够用了
        //可以使用BigInteger这个类来搞定
        long l = 2345646546911L;
        System.out.println("L=" + l);

        BigInteger bigInteger = new BigInteger("23");
        BigInteger bigInteger2 = new BigInteger("10");
        System.out.println(bigInteger);

        //1.在对BigInteger 进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
        //2.可以创建一个要操作的BigInteger 然后进行相应操作,最后用一个BigInteger来接受
//        BigInteger add = bigInteger.add(new BigInteger("10"));
        BigInteger add = bigInteger.add(bigInteger2);
        System.out.println(add);//加

        BigInteger subtract = bigInteger.subtract(bigInteger2);
        System.out.println(subtract);//减


        BigInteger multiply = bigInteger.multiply(bigInteger2);
        System.out.println(multiply);//乘

        BigInteger divide = bigInteger.divide(bigInteger2);
        System.out.println(divide);//除
    }

}

二、BigDecimal的常用方法

  1. add
  2. subtract
  3. multiply
  4. divide
package com.hspedu.bignum_;

import java.math.BigDecimal;

/**
 * @author DL5O
 * @version 1.0
 */
public class BigDecimal_ {
    public static void main(String[] args) {
        //我们需要一个很高的精度的数,double 不够用,那么就使用BigDecimal

       /* double d = 199.655645648657465d;
        System.out.println(d);//199.65564564865747*/

        BigDecimal bigDecimal = new BigDecimal("1999.111111999999999999999999999");
        BigDecimal bigDecimal1 = new BigDecimal("1.1");
        System.out.println(bigDecimal);

        //老韩解读
        //1.如果对 BigDecimal 进行运算也不能直接使用 +-*/,比如加减乘除
        //2.创建一个需要操作的 BigDecimal 然后调用相应的方法即可
        BigDecimal add = bigDecimal.add(bigDecimal1);
        System.out.println(add);

        BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
        System.out.println(subtract);

        System.out.println(bigDecimal.multiply(bigDecimal1));
        System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));
        //可能抛出异常,可能会有小数点除不尽的情况,无限循环小数,ArithmeticException
        //如何解决:在调用divide指定精度即可,如果有无限循环小数,就会保留 分子的精度
    }
}
posted @ 2022-03-04 12:42  DL50  阅读(34)  评论(0编辑  收藏  举报