各自努力,最高处见!加油!
BigInteger和BigDecimal类
BigInteger和BigDecimal类的介绍
应用场景:
- BigInteger适合保存比较大的整型。
- BigDecimal适合保存精度更高的浮点型。
BigInteger及相关运算
在对BigInteger进行加减乘除的时候,需要使用对应的方法,不能直接进行加减乘除
import java.math.BigInteger;
public class BigInteger_ {
public static void main(String[] args) {
String str="237788888888888888888888888888";
String str2="100";
BigInteger bigInteger = new BigInteger(str);
System.out.println(bigInteger);
BigInteger bigInteger1 = new BigInteger(str2);
BigInteger sum=bigInteger.add(bigInteger1);//加法
System.out.println("和:"+sum);
BigInteger subtract_=bigInteger.subtract(bigInteger1);//减法
System.out.println("差:"+subtract_);
BigInteger multiply_=bigInteger.multiply(bigInteger1);//乘法
System.out.println("积:"+subtract_);
BigInteger divide_=bigInteger.divide(bigInteger1);//乘法
System.out.println("商:"+divide_);
}
}
BigDecimal及相关运算
需要保存一个精度很高的数时,double不够用。
import java.math.BigDecimal;
public class BigDecimal_ {
public static void main(String[] args) {
BigDecimal bigDecimal = new BigDecimal("568888.8888888888888888888888888");
BigDecimal bigDecimal1 = new BigDecimal("100");
System.out.println(bigDecimal.add(bigDecimal1));
System.out.println(bigDecimal.subtract(bigDecimal1));
System.out.println(bigDecimal.multiply(bigDecimal1));
System.out.println(bigDecimal.divide(bigDecimal1));
}
}
注意:除法除不尽的时候会抛出异常。解决:在调用的时候指定精度即可。
System.out.println(bigDecimal.divide(bigDecimal1));//除法除不尽的时候会抛出异常。解决:在调用的时候指定精度即可。
System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));//保留分子的精度,本例中为bigDecimal的精度