Java review(4) Java 高精度类型 BigInteger、BigDecimal
- BigInteger支持任意大小的整数
@Test
public void test1() throws Exception {
BigInteger bigInteger = new BigInteger(new byte[] {127, 0, 0, 0});
System.out.println(bigInteger);
System.out.println(bigInteger.toString(2));
// 2130706432
// 二进制:开头的0被省略了,完整应该是:01111111 00000000 00000000 00000000
// 1111111 00000000 00000000 00000000
// 负数
bigInteger = new BigInteger(-1, new byte[] {127, 0, 0, 0});
System.out.println(bigInteger);
// -2130706432
// 使用字符串构造:(字符串,进制)或者(字符串)/默认十进制
bigInteger = new BigInteger("aaaaaaaaaaaaaa", 16);
System.out.println(bigInteger);
System.out.println(bigInteger.toString(2));
System.out.println(bigInteger.toString(16));
// 10101010101010101010101010101010101010101010101010101010
// aaaaaaaaaaaaaa
BigInteger b1 = new BigInteger("123456789012345678901234567890");
BigInteger b2 = new BigInteger("123456789012345678901234567890");
// 加减乘除取余
System.out.println(b1.add(b2));
System.out.println(b1.subtract(b2));
System.out.println(b1.multiply(b2));
System.out.println(b1.divide(b2));
System.out.println(b1.mod(b2));
// 246913578024691357802469135780
// 0
// 15241578753238836750495351562536198787501905199875019052100
// 1
// 0
// 兼容Math
System.out.println(b1.gcd(b2));
System.out.println(b1.pow(3));
System.out.println(b1.abs());
// ...
// 123456789012345678901234567890
// 1881676372353657772546716040589641726257477229849409426207693797722198701224860897069000
// 123456789012345678901234567890
// 兼容与或非等二进制运算,除了 >>> 无符号移位
System.out.println(b1.and(b2));
System.out.println(b1.or(b2));
System.out.println(b1.not());
System.out.println(b1.xor(b2));
// 123456789012345678901234567890
// 123456789012345678901234567890
// -123456789012345678901234567891
// 0
}
- BigDecimal支持任意大小的浮点数
@Test
public void test2() throws Exception {
BigDecimal bigDecimal = new BigDecimal("1234567890E-123");
System.out.println(bigDecimal);
// 1.234567890E-114
// 使用BigDecimal(BigInteger unscaledVal, int scale)构造
BigDecimal b1 = new BigDecimal(new BigInteger("123123123123"), 10);
System.out.println(b1);
// 12.3123123123
// scale标识小数点偏移位置
BigDecimal b2 = new BigDecimal(new BigInteger("1231233"), 10);
// 可以设置保留位数和舍去规则
System.out.println(b1.divide(b2, 5, RoundingMode.DOWN));
// 99999.85634
// 其余基本操作和BigInteger类似
// ...
}
版权声明
本文章由作者“衡于墨”创作,转载请注明出处,未经允许禁止用于商业用途
发布时间:2019年11月28日 11:37:29
备案号:
闽ICP备19015193号-1
关闭特效
评论区#
还没有评论哦,期待您的评论!
引用发言