一、BigInteger(高精度整型)
package com.haobi;
import java.math.BigInteger;
/*
* BigInteger:可以让超过Integer范围内的数进行运算
*/
public class Test1 {
public static void main(String[] args) {
BigInteger b1 = new BigInteger("111111111111111111111111111111");
BigInteger b2 = new BigInteger("222222222222222222222222222222");
System.out.println("加法:"+b1.add(b2));//+
System.out.println("减法:"+b2.subtract(b1));//-
System.out.println("乘法:"+b1.multiply(b2));//*
System.out.println("除法:"+b2.divide(b1));//除
BigInteger[] arr = b1.divideAndRemainder(b2);
System.out.println("取除数:"+arr[0]);
System.out.println("取余:"+arr[1]);
}
}
//程序输出结果如下:
加法:333333333333333333333333333333
减法:111111111111111111111111111111
乘法:24691358024691358024691358024641975308641975308641975308642
除法:2
取除数:0
取余:111111111111111111111111111111
补充:大数比较大小一般采用compareTo()方法
A.compareTo(B) < 0 //等价于 A-B<0
二、BigDecimal(高精度浮点型)
BigDecimal的加、减、乘、除操作的方法与BigInteger相同,如上所示。
下面两个方法是基于BigDcimal除法操作的结果所连缀的方法。
方法一:用于移除除法结果末尾的0
stripTrailingZeros() //用于移除末尾多余的0
方法二:用于控制除法结果不使用科学计数法
toPlainString() //控制不使用科学计数法输出