BigInteger 和 BigDecimal 介绍
应用场景
- BigInteger适合保存比较大的整型
- BigDecimal适合保存精度更高的浮点型(小数)
package com.tao.biginteger_;
import java.math.BigInteger;
/**
* Create By 刘鸿涛
* 2022/1/3 23:14
*/
public class BigInteger_ {
public static void main(String[] args) {
//Long 不够用时
long l = 2323232454587787877L; //不能再加了!!
System.out.println("l = " + l);
//BigInteger
BigInteger bigInteger = new BigInteger("464664648574744464646464646464");//注意引号
System.out.println(bigInteger);
//1.在对 BigInteger 进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
//2.创建一个要操作的 BigInteger 然后进行相应的操作
BigInteger add_ = new BigInteger("1");
add_ = bigInteger.add(add_);
System.out.println(add_);
BigInteger subtract_ = bigInteger.subtract(add_);
System.out.println(subtract_);
BigInteger bigInteger1 = new BigInteger("1");
BigInteger multiply_ = bigInteger.multiply(bigInteger1);
System.out.println(multiply_);
BigInteger divide_ = bigInteger.divide(bigInteger1);
System.out.println(divide_);
}
}
l = 2323232454587787877
464664648574744464646464646464
464664648574744464646464646465
-1
464664648574744464646464646464
464664648574744464646464646464
package com.tao.biginteger_;
import java.math.BigDecimal;
/**
* Create By 刘鸿涛
* 2022/1/3 23:33
*/
public class BigDecimal_ {
public static void main(String[] args) {
//当我们需要保存一个精度很高的数时,double 不够用
//可以使用 BigDecimal
double d = 1999.111111111111111111111111111111d;
System.out.println(d); //1999.111111111111
BigDecimal bigDecimal = new BigDecimal("1999.11");
System.out.println(bigDecimal);
//1.如果对 BigDecimal 进行运算,比如 + - * /,需要使用对应的方法
//2.需要创建一个需要操作的 BigDecimal 然后调用相应方法
BigDecimal bigDecimal1 = new BigDecimal("1.1");
System.out.println(bigDecimal.add(bigDecimal1));
System.out.println(bigDecimal.subtract(bigDecimal1));
System.out.println(bigDecimal.multiply(bigDecimal1));
// System.out.println(bigDecimal.divide(bigDecimal1)); //可能抛出异常,因为除不尽
//解决方案
//在调用divide方法时,指定精度即可,BigDecimal.ROUND_CEILING
//如果有无限循环小数,就会保留 分母的 精度
System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));
}
}
1999.111111111111
1999.11
2000.21
1998.01
2199.021
1817.38