In this Java program, we will learn to convert the double variables to a integer value. In Java, you can convert a double to an int using several different methods.
Using type casting
double d = 42.5; int number = (int) d;
This method involves explicitly casting the double to an int. The double value is converted to an int value and stored in the int variable number. Note that when you cast double to int, it will truncate the decimal part.
Using the Math.round() method
double d = 42.5; int number = (int) Math.round(d);
This method rounds the double value to the nearest int value, and then converts it to int.
Using Integer.valueOf() method with Double.toString()
double d = 42.5; int number = Integer.valueOf(Double.toString(d).split("\\.")[0]);
This method converts double to string using Double.toString() method and then splitting it by "." and get the first element which is the integer part.
Using Double.intValue() method
double d = 42.5; int number = d.intValue();
This method is similar to floatValue() and longValue() method, it will return the value of this Double as an int.
It is important to note that, if the double value is too large to be represented as an int, the result will be the largest possible int value (2147483647 or -2147483648) or Integer.MAX_VALUE or Integer.MIN_VALUE depending on the sign of the double. If the double is NaN or infinite, it will throw NumberFormatException
Java Program to Convert Double to Integer
public class DoubleToIntExample { public static void main(String[] args) { double d = 42.5; // Using type casting int number1 = (int) d; System.out.println("Type casting: " + number1); // Using Math.round() method int number2 = (int) Math.round(d); System.out.println("Math.round(): " + number2); // Using Integer.valueOf() method int number3 = Integer.valueOf(Double.toString(d) .split("\\.")[0]); System.out.println("Integer.valueOf(): " + number3); // Using Double.intValue() method int number4 = (int) d; System.out.println("Double.intValue(): " + number4); } }Output
Type casting: 42 Math.round(): 43 Integer.valueOf(): 42 Double.intValue(): 42
This program defines a double variable d with the value 42.5. Then, it demonstrates the use of type casting, the Math.round() method, the Integer.valueOf() method and Double.intValue() method for converting the double to an int.