大数:
如果基本的整数和浮点数精度不能够满足需求,那么可以使用java.math包中两个很有用的类:
BigInteger 和 BigDecimal。这两个类可以处理包含任意长度数字序列的数值。
BigInteger类实现任意精度的
整数运算
BigDecimal类实现任意精度的
浮点数运算。
BigInteger bigInteger = new BigInteger("412322312312121212121");//1.在对 BigInteger进行加减乘除的时候,要使用对应的方法,不能直接+ - * /。//2. add 加substract 减multiply 乘divide 除BigDecimal bigDecimal = new BigDecimal("45654545646546.1212121212121");BigDecimal bigDecimal1 = new BigDecimal("1.1");//这里会抛出ArithmeticException//原因是 运算的结果是一个无限循环小数,无法被除尽//System.out.println(bigDecimal.divide(bigDecimal1));//解决方法://在调用divide 方法时,使用 RoundingMode.CEILING 指定精度即可//如果有无限循环小数时,就会保留 分子 的精度System.out.println(bigDecimal.divide(bigDecimal1 , RoundingMode.CEILING));
代码示例:
import java.math.*;
public class BigNumber{
public static void main(String[] args) {
BigInteger bigInteger = new BigInteger("412322312312121212121");
BigInteger bigInteger2 = new BigInteger("99");
BigInteger add = bigInteger.add(bigInteger2); //加
BigInteger subtract = bigInteger.subtract(bigInteger2); //减
BigInteger multiply = bigInteger.multiply(bigInteger2); //乘
BigInteger divide = bigInteger.divide(bigInteger2); //除
}
}