注意事项:
1.大数之间的运算,不能直接进行,要使用相对应的方法,就像下边代码的例子
2.创建一个需要操作的BigInterger对象,调用相应的方法即可。
3.BigInterger类只用于保存整型
public class Big_number01 {
public static void main(String[] args) {
BigInteger bigInteger01 = new BigInteger("149999999999999999999999999999");
BigInteger bigInteger02 = new BigInteger("100");
BigInteger sql01 = bigInteger01.add(bigInteger02);//大数求和
BigInteger sql02 = bigInteger01.subtract(bigInteger02);//求差
BigInteger sql03 = bigInteger01.multiply(bigInteger02);//乘
BigInteger sql04 = bigInteger01.divide(bigInteger02);//除
System.out.println("和:"+sql01);
System.out.println("差:"+sql02);
System.out.println("乘:"+sql03);
System.out.println("除:"+sql04);
}
}
运行结果:
注意事项:
1.使用方式与BigInter类相似。
2.使用除法时,可以会因为除不尽产生无限循环小数而报错(因为BigDecimal类能保存很高的精度),这时要指定精度。
double r1 = 12.33333333333333333333333333;
System.out.println( "r1="+r1);
普通方法会损失小数点后的精度,以上代码的运行结果是:
接下来看,看大数浮点数之间的简单运算,同整数大数一样,不能直接运算,也要调用对应的方法:
public class Big_number02 {
public static void main(String[] args) {
BigDecimal bigDecimal01 = new BigDecimal("12.33333333333333333333333333");
BigDecimal bigDecimal02 = new BigDecimal("3");
System.out.println("r1="+bigDecimal01);//精度不会损失
System.out.println("加="+bigDecimal01.add(bigDecimal02));
System.out.println("减="+bigDecimal01.subtract(bigDecimal02));
System.out.println("乘="+bigDecimal01.multiply(bigDecimal02));
}
}
运行结果:r1的精度并没有损失
单独看除法:
public static void main(String[] args) {
BigDecimal bigDecimal01 = new BigDecimal("12.33333333333333333333333333");
//BigDecimal bigDecimal02 = new BigDecimal("3");
BigDecimal bigDecimal02 = new BigDecimal("11");
System.out.println("除="+bigDecimal01.divide(bigDecimal02));
//被除数是3的话,能除尽
// 运行结果为:除=4.11111111111111111111111111
//被除数是11的话,除不尽,产生一个算数异常:
//异常为:java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
}
除运算可能产生异常的解决方法;
1.调用divide方法时,指定精度即可。
2.BigDecimal.ROUND_CEILING指定精度,如果出现无限循环小数,保留与除数相同的精度
BigDecimal bigDecimal01 = new BigDecimal("12.33333333333333333333333333");
BigDecimal bigDecimal02 = new BigDecimal("11");
// BigDecimal.ROUND_CEILING指定精度,如果出现无限循环小数,保留与除数相同的精度
System.out.println("除="+bigDecimal01.divide(bigDecimal02,BigDecimal.ROUND_CEILING));
//运行结果:除=1.12121212121212121212121213
最后,小弟不才,有错误之处,还请大佬指正,感谢



