BigDecimal intvalueExact() Method in Java
The java.math.BigDecimal.intValueExact() is an inbuilt function which converts this BigDecimal to an integer value as well as checks for the lost information. This function throws an 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 an integer value.
public int intValueExact()
Parameters: This function accepts no parameters.
Return Value: This function returns the integer value of this BigDecimal.
Exception: The function throws an ArithmeticException if there is a non-zero fractional part in this BigDecimal or its value is too big to be represented as an integer.
Input : "19878124" Output : 19878124 Input : "721111" Output : 721111
Below programs illustrate the use of java.math.BigDecimal.intValueExact() method:
Exact Integer Value of 19878124 is 19878124 Exact Integer Value of 721111 is 721111
Note: Unlike intValue() function which function discards any fractional part of this BigDecimal and returns only the lower-order 32 bits when result of the conversion is too big to be represented as a an integer value, this function throws Arithmetic Exception in such occurrences.
Program 2: This program will illustrate when this function throws Exception.
Output by intValue() Function The Integer Value of 3232435121868179 is -214774381 The Integer Value of 84561789104423214 is -920387282 Output by intValueExact() 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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.