BigInteger 和 BigDecimal 类
二者共有的常见方法
方法 功能 add 加 subtract 减 multiply 乘 divide 除
注意点:传参类型必须是类对象
一、BigInteger
1. 作用:适合保存比较大的整型数
2. 使用说明
3. 代码示例
import java. math. BigInteger ;
public class main {
public static void main ( String [ ] args) {
BigInteger bigInteger = new BigInteger ( "999999999999999999999999" ) ;
System . out. println ( bigInteger) ;
BigInteger bigInteger1= new BigInteger ( "9" ) ;
System . out. println ( "add:" + bigInteger. add ( bigInteger1) ) ;
System . out. println ( "subtract:" + bigInteger. subtract ( bigInteger1) ) ;
System . out. println ( "multiply:" + bigInteger. multiply ( bigInteger1) ) ;
System . out. println ( "divide:" + bigInteger. divide ( bigInteger1) ) ;
}
}
999999999999999999999999
add:1000000000000000000000008
subtract:999999999999999999999990
multiply:8999999999999999999999991
divide:111111111111111111111111
二、BigDecimal
1. 作用:适合保存高精度 浮点数(小数)
2. 使用说明
3. 注意点
在BigDecimal
使用除法 的时候,会出现除不尽 (无限循环小数)的情况,这个时候会抛出异常(ArithmeticException
)
解决方法
传参时候传入BigDecimal.ROUND_CEILING)
,这个时候结果的精度 就会和分子保持一致
代码示例
import java. math. BigDecimal ;
public class main {
public static void main ( String [ ] args) {
BigDecimal bigDecimal = new BigDecimal ( "99.8888888888889999999" ) ;
System . out. println ( bigDecimal) ;
BigDecimal bigDecimal1= new BigDecimal ( "7" ) ;
System . out. println ( "add:" + bigDecimal. add ( bigDecimal1) ) ;
System . out. println ( "subtract:" + bigDecimal. subtract ( bigDecimal1) ) ;
System . out. println ( "multiply:" + bigDecimal. multiply ( bigDecimal1) ) ;
System . out. println ( "divide:" + bigDecimal. divide ( bigDecimal1, BigDecimal . ROUND_CEILING ) ) ;
}
}
99.8888888888889999999
add:106.8888888888889999999
subtract:92.8888888888889999999
multiply:699.2222222222229999993
divide:14.2698412698412857143