BigInteger:大整数
在Java中整型有4中类型:byte、short、int、long
在底层占用字节个数:1、2、4、8
BigInteger的构造方法
public BigInteger(int num,Random rnd)获取随机大整数,范围:[0~2的num次方-1]
public BigInteger(String val)获取指定大整数
public BigInteger(String val,int radix)获取指定进制的大整数
public static BigInteger valueOf(long val)静态方法获取BigInteger对象,内部有优化
对象一旦创建,内部记录的值不能发生改变
//获取随机大整数 Random r = new Random(); BigInteger bd1 = new BigInteger(4, r); System.out.println(bd1); //获取指定大整数 //字符串中必须是整数,否则会报错 BigInteger bd2=new BigInteger("99999999999999999999999"); System.out.println(bd2); //获取指定进制的大整数 //字符串中的数字必须是整数 //字符串中的数字必须跟进制吻合,否则会报错 BigInteger bd3=new BigInteger("100",10); System.out.println(bd3); //静态方法获取 //能表示的范围比较小,在long 的范围下取值,超出会报错 //在内部对常用的数字-16-16进行了优化 //提前吧这个范围的数字创建好了对象,多次获取不会创建新的 BigInteger bd5=BigInteger.valueOf(100); System.out.println(bd5);
总结:
如果BigInteger表示的数字没有超出long的范围,可以用静态方法获取。
如果BigInteger表示的超出long的范围,可以用构造方法获取。
只要进行计算都会产生一个新的BigInteger对象。
成员方法:
//创建两个BigInteger对象 BigInteger bd1 = BigInteger.valueOf(10); BigInteger bd2 = BigInteger.valueOf(3); //加法 add //减法 subtract //乘法 multiply //除法 divide获取商 BigInteger bd3 = bd1.add(bd2); System.out.println(bd3); //除法 divideAndRemainder获取商和余数,返回一个数组,0索引为商,1索引为余数 BigInteger[] arr = bd1.divideAndRemainder(bd2); System.out.println(arr.length); System.out.println(arr[0]); System.out.println(arr[1]); //比较是否相同 equals boolean result = bd1.equals(bd2); System.out.println(result); //次幂 pow BigInteger bd5 = bd1.pow(2); System.out.println(bd5); //max BigInteger max = bd1.max(bd2); System.out.println(max); //intValue BigInteger bd6 = BigInteger.valueOf(1000); int i=bd6.intValue(); System.out.println(i);
BigDecimal
计算机中的小数,是由二进制的整数部分和小数部分组成的。
作用:
用于小数的精确计算,也可以记录很大的小数
构造方法获取BigDecimal对象
Public BigDecimal(double val)
Public BigDecimal(String val)
静态方法获取 BigDecimal对象
public static BigDecimal valueOf(double val)
//1.通过传递double类型的小数来创建对象 //细节: //这种方式有可能不精确,不建议使用 BigDecimal bd1 = new BigDecimal(0.01); BigDecimal bd2 = new BigDecimal(0.09); System.out.println(bd1); System.out.println(bd2); //2.通过传递字符串来创建对象 BigDecimal bd3 = new BigDecimal("0.01"); BigDecimal bd4 = new BigDecimal("0.09"); System.out.println(bd3); System.out.println(bd4); BigDecimal bd5 = bd3.add(bd4); System.out.println(bd5); //3.通过静态方法获取对象 BigDecimal bd6 = BigDecimal.valueOf(10); BigDecimal bd7 = BigDecimal.valueOf(10); System.out.println(bd6); System.out.println(bd6 == bd7); //细节: //如果要表示的数字不大,没有超出double的范围,建议使用静态方法 //超出建议用构造方法 //如果传递的是0~10之间的整数,会返回Java已经创建好的对象