How to Convert double to int in Java
The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion. The conversion from double to int is called explicit conversion or narrowing conversion.
We know that the double data type can contain decimal digits. The decimal digits are truncated when we convert double value with decimal digits to int value.
Double value can contain decimal digits, so when we convert double value with decimal digits to int value, the decimal digits are truncated. There are two ways to convert double to int.
- Using Typecasting
- Using intValue() method
Using Typecasting
Typecasting is used to perform the conversion between two incompatible types. Typecast operator (data type) is used to perform typecasting in Java. The signature of typecasting is:
data_type variable_name = (target data type) variable to convert;
Example
In the following example, we have taken a variable pi of type double and initialized the value of pi 3.14159265359 to it. pi2 is a variable of type int which stores the converted value of pi. (int) is a typecast operator. pi is a variable which we want to convert into int type. The first println statement prints the pi value before truncation of decimal digits. The second println statement prints the pi value after truncation of decimal digits.
public class doubleTointExample { public static void main(String args[]) { double pi=3.14159265359; int pi2=(int)pi; performing typecasting System.out.println("Before truncation: " +pi); System.out.println("After truncation: " +pi2); } }
Output
Before truncation: 3.14159265359 After truncation: 3
Using intValue() method
The intValue() is the built-in method of Integer wrapper class which belong to the java.lang package. It does not accept any parameter. It returns the value which is represented by the object after conversion to int type. Double wrapper class truncates all digits after the decimal point.
Example
In the following example, Double is a wrapper class, and d is an object of Double class. The new is a keyword that creates an object dynamically. Double() automatically calls the constructor of Double class. The constructor parses a double value as an argument. We have taken another variable i of type int which stores the converted int value. The object d invokes the intValue() method of Integer class, and converts double type into int type. The first println statement prints the value before truncation. The second println statement prints the value after truncation.
public class doubleTointExample1 { public static void main(String args[]) { //Double d= 6782.432; //use either this line or the line next to it both works same Double d=new Double(6782.432); int i=d.intValue(); //using intValue() method System.out.println("Before truncation: "+d); System.out.println("After truncation: "+i); } }
Output
Before truncation: 6782.432 After truncation: 6782