Search code examples
javatype-conversionprecisionbigdecimaltruncation

Java BigDecimal data converting to opposite sign long


According to the Java 7 documentation, the method longValue from class java.math.BigDecimal can return a result with the opposite sign.

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.

In what case is it possible?


Solution

  • It is possible whenever the value of the BigDecimal is larger than what a long can hold.

    Example:

    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