BigInteger和BigDecimal

52 阅读1分钟

BigInteger

// OpenJDK 源码中的关键字段
public class BigInteger {
    // 符号位:1表示负数,0表示零,1表示正数
    final int signum;

    // 存储绝对值的大端序(big-endian)int数组
    -   采用 **二进制补码** 形式存储
    -   最高位int的最高bit表示符号(非标准补码实现)
    -   例如:数字 `12345678901234567890` 可能存储为 `[0xAB54A98C, 0xEB1F0AD2]`
    final int[] mag; 运算时对其数组位置然后分段运算

    // 其他辅助字段...
}

加减乘除等运算

BigDecimal

private final BigInteger intVal;     // 未缩放整数值
private final int scale;            // 小数位数
private transient int precision;    // 精度(非final,延迟计算)

举例:

BigInteger num1 = new BigInteger("123456");
//signum 1
//mag 01 E2 40 [1, -30, 64]
BigDecimal decimal = new BigDecimal("5.20E+3");//5200
BigDecimal decimal1 = new BigDecimal("1234.560");
BigDecimal decimal2 = new BigDecimal("-789.210");
BigDecimal decimal3 = new BigDecimal("123.456789",new MathContext(4));
// intVal   sacle  precision
   520        -1      3   
   1234560     3      7
   -789210     3      6
   1235        1      4

image.png

运算操作

image.png