Java BigDecimal 数据转换为相反符号 long

Java BigDecimal data converting to opposite sign long

根据 Java 7 documentation,方法 longValue 来自 class java.math.BigDecimal可以return一个符号相反的结果。

Converts this BigDecimal to a long. This conversion is analogous to the narrowing primitive conversion from double to short as defined in section 5.1.3 of The Java™ Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

什么情况下可以?

只要 BigDecimal 的值大于 long 可以容纳的值,就有可能。

示例:

BigDecimal num = new BigDecimal(Long.MAX_VALUE);
System.out.println(num);                  // prints: 9223372036854775807
System.out.println(num.longValue());      // prints: 9223372036854775807

num = num.add(BigDecimal.TEN);            // num is now too large for long
System.out.println(num);                  // prints: 9223372036854775817
System.out.println(num.longValue());      // prints: -9223372036854775799
System.out.println(num.longValueExact()); // throws: ArithmeticException: Overflow

如果大于long的最大值就会发生

BigDecimal dec = new BigDecimal(Long.MAX_VALUE +1);
System.out.println(dec.longValue());