一、概念
java.math.*包中提供了大数类,其理论上可以存储无限位的大数,只要内存足够的话。 大数类又分为整数
和浮点数
.即BigInteger and BigDecimal 不能直接进行运算,整数和浮点数不能混合运算.
二、常用方法
1.常见用法
1.1BigInteger
import java. math. BigInteger ;
public class Demo {
public static void main ( String [ ] args) {
BigInteger bi1 = new BigInteger ( "123456789" ) ;
BigInteger bi2 = new BigInteger ( "987654321" ) ;
System . out. println ( "加法操作:" + bi2. add ( bi1) ) ;
System . out. println ( "减法操作:" + bi2. subtract ( bi1) ) ;
System . out. println ( "乘法操作:" + bi2. multiply ( bi1) ) ;
System . out. println ( "除法操作:" + bi2. divide ( bi1) ) ;
System . out. println ( "最大数:" + bi2. max ( bi1) ) ;
System . out. println ( "最小数:" + bi2. min ( bi1) ) ;
BigInteger result[ ] = bi2. divideAndRemainder ( bi1) ;
System . out. println ( "商是:" + result[ 0 ] +
";余数是:" + result[ 1 ] ) ;
System . out. println ( a. equals ( new BigInteger ( "99" ) ) ) ;
}
}
2.2BigDecimal
import java. math. BigDecimal ;
public class Demo {
public static void main ( String [ ] args) {
System . out. println ( "加法运算:" + MyMath . round ( MyMath . add ( 10.345 , 3.333 ) , 1 ) ) ;
System . out. println ( "减法运算:" + MyMath . round ( MyMath . sub ( 10.345 , 3.333 ) , 3 ) ) ;
System . out. println ( "乘法运算:" + MyMath . round ( MyMath . mul ( 10.345 , 3.333 ) , 4 ) ) ;
System . out. println ( "除法运算:" + MyMath . div ( 10.345 , 3.333 , 3 ) ) ;
}
}
class MyMath {
public static double add ( double d1, double d2) {
BigDecimal b1 = new BigDecimal ( d1) ;
BigDecimal b2 = new BigDecimal ( d2) ;
return b1. add ( b2) . doubleValue ( ) ;
}
public static double sub ( double d1, double d2) {
BigDecimal b1 = new BigDecimal ( d1) ;
BigDecimal b2 = new BigDecimal ( d2) ;
return b1. subtract ( b2) . doubleValue ( ) ;
}
public static double mul ( double d1, double d2) {
BigDecimal b1 = new BigDecimal ( d1) ;
BigDecimal b2 = new BigDecimal ( d2) ;
return b1. multiply ( b2) . doubleValue ( ) ;
}
public static double div ( double d1, double d2, int len) {
BigDecimal b1 = new BigDecimal ( d1) ;
BigDecimal b2 = new BigDecimal ( d2) ;
return b1. divide ( b2, len, BigDecimal . ROUND_HALF_UP) . doubleValue ( ) ;
}
public static double round ( double d, int len) {
BigDecimal b1 = new BigDecimal ( d) ;
BigDecimal b2 = new BigDecimal ( 1 ) ;
return b1. divide ( b2, len, BigDecimal . ROUND_HALF_UP) . doubleValue ( ) ;
}
} ;