1. Using intValueExact() [Recommended]
2. Using intValue()
3. Using toBigInteger()
Read Also: Convert Integer to BigDecimal in Java
Let's dive deep into the topic:
Convert BigDecimal to Integer in Java
1. Using intValueExact() method
You can easily use BigDecimal class intValueExact() method to convert BigDecimal to Integer in Java. BigDecimal.intValueExact()
Note: BigDecimal class intValueExact() method will throw ArithmeticException if BigDecimal has a nonzero fractional part or is out of the possible range for an int result.
Below is the step-by-step example to convert BigDecimal to Integer in Java using the intValueExact() method.
import java.math.BigDecimal;
public class BigDecimalToInteger {
public static void main(String args[]) {
// Creating BigDecimal Object using Constructor
BigDecimal bd = new BigDecimal("34563245");
// Converting BigDecimal to Integer using intValueExact()
Integer i = bd.intValueExact();
// Displaying Integer
System.out.println("Converted BigDecimal to Integer: "+i);
}
}
Output:
Converted BigDecimal to Integer: 34563245
2. Using intValue() method
You can also use BigDecimal class intValue() method to convert BigDecimal to Integer in Java. BigDecimal.intValue()
Note: Unlike the intValueExact() method, BigDecimal class intValue() method will not throw ArithmeticException even if BigDecimal has a nonzero fractional part or is out of the possible range for an int result.
Below is the step-by-step example to convert BigDecimal to Integer in Java using the intValue() method.
import java.math.BigDecimal;
public class BigDecimalToInteger2 {
public static void main(String args[]) {
// Creating BigDecimal Object using Constructor
BigDecimal bd = new BigDecimal("439745743");
// Converting BigDecimal to Integer using intValue()
Integer num = bd.intValue();
// Printing Integer
System.out.println("Converted BigDecimal to Integer: "+ num);
}
}
Output:
Converted BigDecimal to Integer: 439745743
3. Using toBigInteger() method
You can also use BigDecimal class toBigInteger() method to convert BigDecimal to Integer in Java.Below is the step-by-step example to convert BigDecimal to Integer in Java using the toBigInteger() method.
import java.math.BigDecimal;
public class BigDecimalToInteger3 {
public static void main(String args[]) {
// Creating BigDecimal Object
BigDecimal bd = new BigDecimal("897347893");
// Converting BigDecimal to Integer using toBigInteger() method
Integer num = bd.toBigInteger().intValueExact();
// Printing Integer value
System.out.println("Converted BigDecimal to Integer: "+ num);
}
}
Output:
Converted BigDecimal to Integer: 897347893
That's all for today, please mention in the comments in case you have any questions related to converting BigDecimal to Integer in Java.