What is BigDecimal.longValueExact() method in Java?
BigDecimal is an immutable arbitrary-precision signed decimal number. It contains an arbitrary precision integer unscaled value and a 32-bit integer scale. For example in the value 10.11, 1011 is the unscaled value and 2 is the scale. The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
Read more at about
BigDecimalclass here.
The longValueExact method of the BigDecimal class converts the value of the BigDecimal to a long value.
An ArithmeticException is thrown:
- If the value contains non-zero fractional parts.
- If the value is larger than the maximum value a
longtype can hold.
Syntax
public long longValueExact()
This method doesn’t take any arguments.
This method returns the BigDecimal value as a long value.
Code
The code below demonstrates how to use the longValueExact method:
import java.math.BigDecimal;class LongValueExact {public static void main( String args[] ) {BigDecimal val1 = new BigDecimal("10");BigDecimal val2 = new BigDecimal("10.10");BigDecimal val3 = new BigDecimal("9223372036854775808");System.out.println("longValueExact of " + val1 + " : "+ val1.longValueExact());try{System.out.println("longValueExact of " + val2 + " : "+ val2.longValueExact());} catch(Exception e) {System.out.println("\nException while converting the " + val2 + " - \n" + e);}try{System.out.println("longValueExact of " + val3 + " : "+ val3.longValueExact());} catch(Exception e) {System.out.println("\nException while converting the " + val3 + " - \n" + e);}}}
Explanation
In the code above,
-
We create three
BigDecimalobjectval1,val2, andval3with value10,10.10, and9223372036854775808respectively. -
We call the
longValueExactmethod of theval1object. This will return theBigDecimalvalue aslong. The value10can be stored inlongand has no non-zero fraction so there will be no exception. -
We call the
longValueExactmethod of theval2object. The value10.10contains a non-zero fractional part so, anArithmeticExceptionis thrown. -
We call the
longValueExactmethod of theval3object. The value9223372036854775808is too large to be stored inlongso anArithmeticExceptionis thrown.