BigDecimal和BigInteger有什么区别?Java大数运算全解析
作者:不冻港406
还在为Java小数计算精度问题头疼吗?本文详细讲解BigDecimal的构造方法、valueOf静态方法以及BigInteger的使用,帮你彻底搞懂如何避免精度丢失,同时,我们还梳理了各种舍入模式,让你在除不尽时也能从容应对,是Java开发者不可错过的实用指南
BigInteger
1.构造方法
1. public BigDecimal(int num, Random rnd) | 获取随机大整数,范围:[0 ~ 2^31 - 1]
Random r=new Random(); BigInteger bi=new BigInteger(4,r);
2.public BigDecimal(String val) | 获取指定的大整数
BigInteger bi=new BigInteger("265465311564356645635446351355");3.public BigDecimal(String val, int radix) | 获取指定进制的大整数
BigInteger bi=new BigInteger("101011101",2);字符串必须满足进制的格式,例如二进制字符串不能出现比1大的字符;
System.out.println(bi);
以十进制输出
4.public static BigDecimal valueOf (long val) | 静态方法获取BigInteger的对象,内部有优化
BigInteger bigInteger = BigInteger.valueOf(100L); System.out.println(bigInteger);
这个方法只能表示long取值范围内的值
并且这个方法在内部做了优化,在-16到16范围内已经创建好了对象,多次获取不会创建新的(地址值相同)
2.创建对象后,对象的值不能发生改变
BigInteger b1 = BigInteger.valueOf(100); System.out.println(b1); BigInteger b2 = BigInteger.valueOf(100); System.out.println(b2); BigInteger re = b1.add(b2); System.out.println(re); System.out.println(b1);
在b1调用add方法后,b1的值保持不变
3.常见成员方法
public BigInteger add(BigInteger val) | 加法 public BigInteger subtract(BigInteger val)| 减法 public BigInteger multiply(BigInteger val)| 乘法 public BigInteger divide(BigInteger val) | 除法,获取商 public BigInteger[] divideAndRemainder(BigInteger val) | 除法,获取商和余数 public boolean equals(Object x) | 比较是否相同 public BigInteger pow(int exponent) | 次幂 public BigInteger max/min(BigInteger val) | 返回较大值/较小值 public int intValue() | 转为int类型整数,超出范围数据有误
除了equals,pow,其余方法参数均为BigInteger类,intValue无参数
BigDecimal
System.out.println(0.09+0.01);
0.09999999999999999
一般的小数计算是不精确的
一个数的小数部分在计算机中转化为二进制存储时

Bigdecimal可以实现小数的精确运算
BigDecimal bd=new BigDecimal("-1.000");
BigDecimal bd2=new BigDecimal("-1.1200");
BigDecimal re = bd.add(bd2);
System.out.println(re);构造方法
1.传入double类的小数
BigDecimal bd=new BigDecimal(1.100);
结果依旧可能不精确
2.传入字符串类型
BigDecimal bd=new BigDecimal("1.000");3.静态方法valueOf
BigDecimal bd3 = BigDecimal.valueOf(100);可以传入long类或者double类
如果过传递的是0到10之间的整数包含0,包含10,则得到的是已经创建好的对象
(10.0等被看作小数,创建的对象是新的)
成员方法

ctrl+p可以查看方法参数
没有舍入模式的divide方法在除不尽的情况下会报错
BigDecimal re = bd3.divide(bd, 3, RoundingMode.HALF_UP);
UP:远离零方向舍入的舍入模式DOWN:向零方向舍入的舍入模式CEILING:向正无限大方向舍入的舍入模式FLOOR:向负无限大方向舍入的舍入模式
HALF_UP四舍五入
HALF_DOWN五舍六入
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
