如果要进行大数值的数学操作,而又不想因为溢出而出问题,可以尝试使用BigDecimal类。
假设我现在想要进行以下计算:
200,000,000 * 2,000,000,000,000,000,000L * 20,000,000
int testValue = 200000000;
System.out.println("After Standard Multiplication = " +
testValue *
2000000000000000000L *
20000000);
该操作的值为-4176287866323730432,这是不正确的。
通过使用BigDecimal类,您可以消除丢失的位并获得正确的结果。
int testValue = 200000000;
System.out.println("After BigDecimal Multiplication = " +
decimalValue.multiply(
BigDecimal.valueOf(2000000000000000000L).multiply(
BigDecimal.valueOf(testValue))));
使用BigDecimal后,乘法返回正确的结果为:
80000000000000000000000000000000000