The java.math.BigDecimal.longValueExact() is an in-built function which converts this BigDecimal to a long value as well as checks for lost information. This function throws Arithmetic Exception if there is any fractional part of this BigDecimal or if the result of the conversion is too big to be represented as a long value.
public long longValueExact()
Parameters: This function does not accept any parameters.
Return Value: This function returns the long value of this BigDecimal.
Exception: The function throws ArithmeticException if there is a non-zero fractional part in this BigDecimal or its value is too big to be represented as long.
Input : "1987812456121" Output : 1987812456121 Input : "721111" Output : 721111
Below programs illustrate the use of java.math.BigDecimal.longValueExact() method:
Exact Long Value of 267694723232 is 267694723232 Exact Long Value of 721111845617 is 721111845617
Note: Unlike longValue() function which function discards any fractional part of this BigDecimal and the returns only the lower-order 64 bits when result of the conversion is too big to be represented as a long value, this function throws Arithmetic Exception in such occurrences.
Output by longValue() Function The Long Value of 267694723232435121868 is -9006437873208152372 The Long Value of 72111184561789104423 is -1675791733049102041 Output by longValueExact() Function Arithmetic Exception caught
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.