BigInteger:
demo1:
package BigInteger;import java.math.BigInteger;
import java.util.Random;public class demo1 {public static void main(String[] args) {//獲取一個隨機最大整數BigInteger bd1 = new BigInteger(5, new Random());System.out.println(bd1);//獲取一個指定的大整數(字符串里面不能有小數和字符串)BigInteger bd2 = new BigInteger("123456789012345678901234567890");System.out.println(bd2);//3.獲取指定進制的大整數// 細節://1.字符串中的數字必須是整數//2.字符串中的數字必須要跟進制吻合。//比如二進制中,那么只能寫0和1,寫其他的就報錯。BigInteger bd3 = new BigInteger("100", 2);System.out.println(bd3);//4.靜態方法獲取BigInteger的對象,內部有優化// 細節://1.能表示范圍比較小,只能在1ong的取值范圍之內,如果超出1ong的范圍就不行了。BigInteger bd4 = BigInteger.valueOf(1000);System.out.println(bd4);//2.在內部對常用的數字:-16 ~ 16 進行了優化。// 提前把-16~ 16 先創建好BInteger的對象,如果多次獲取不會重新創建新的。BigInteger bd5 = BigInteger.valueOf(16);BigInteger bd6 = BigInteger.valueOf(16);System.out.println(bd5 == bd6);//true,==比的是地址值,所以多次獲取不會重新創建新的。}
}
demo2:
package BigInteger;import java.math.BigInteger;public class demo2 {public static void main(String[] args) {BigInteger bd1 = BigInteger.valueOf(10);BigInteger bd2 = BigInteger.valueOf(5);//加法System.out.println(bd1.add(bd2));//減法System.out.println(bd1.subtract(bd2));//乘法System.out.println(bd1.multiply(bd2));//除法,獲取商System.out.println(bd1.divide(bd2));//獲取商和余數BigInteger[] bd3 = bd1.divideAndRemainder(bd2);System.out.println(bd3[0]+","+bd3[1]);//比較是否相同System.out.println(bd1.equals(bd2));//次冪System.out.println(bd1.pow(4));//max和minSystem.out.println(bd1.max(bd2));System.out.println(bd1.min(bd2));//轉為int類型整數,超出數據范圍有誤System.out.println(bd1.intValue());}
}
BigDecimal
package BigDecimal;import java.math.BigDecimal;public class demo1 {public static void main(String[] args) {//通過傳遞字符串表示的小數來創建對象BigDecimal bd1 = new BigDecimal("3.14");BigDecimal bd2 = new BigDecimal("2.71");System.out.println(bd1);System.out.println(bd2);System.out.println(bd1.add(bd2));//通過靜態方法獲取對象BigDecimal bd3 = BigDecimal.valueOf(3.14);System.out.println(bd3);//細節://1.如果要表示的數字不大,沒有超出double的取值范圍,建議使用靜態方法//2.如果要表示的數字比較大,超出了double的取值范圍,建議使用構造方法//3.如果我們傳遞的是8~18之間的整數,包含8,包含18,那么方法會返回己經創建好的對象,不會重新newSystem.out.println(bd1.add(bd2));System.out.println(bd1.subtract(bd2));System.out.println(bd1.multiply(bd2));//下面這種方法只適合于整除//bd1.divide(bd2);//BigDecimal.ROUND_HALF_UP代表四舍五入System.out.println(bd1.divide(bd2, 2, BigDecimal.ROUND_HALF_UP));}
}