Before proceeding, there are few points that we should know about
- While converting double to an int, the decimal values will be lost ( 3.14 would be converted 3 ).
- Second, whether we want to convert our double to a floor int value ( means converting 3.14 to 3) or a ceil int value ( means 3.14 to 4).
Now, there are multiple ways to convert a double into an int and we are going to discuss all of them one by one
Using Typecasting
We can directly typecast the double into an int and the resulting int will be the floor value of the double number, which means if we typecast 3.14, then we will get 3 as an int value.
public class Codekru {
public static void main(String[] args) {
double d = 3.14;
int i = (int) d; // typecasting
System.out.println("int value = " + i);
}
}
Output –
int value = 3
So, we had converted our double value to an int.
Math.round() function
Method declaration – public static long round(double a)
What does it do and return? It takes a double value into the argument and then returns a long value back.
Here the round() method will round the double value to the closest long value and then we will have to convert the long value to an int.
- So, If we pass 3.14 into the function, then it would be converted to 3.
- And if we pass 3.8 into the function, then it would be converted to 4.
public class Codekru {
public static void main(String[] args) {
double d1 = 3.14;
double d2 = 3.8;
long l1 = Math.round(d1); // function returning long value
int i1 = (int) l1; // using typecasting to convert from long to an int
System.out.println("i1 value = " + i1);
long l2 = Math.round(d2); // function returning long value
int i2 = (int) l2; // using typecasting to convert from long to an int
System.out.println("i2 value = " + i2);
}
}
Output –
i1 value = 3
i2 value = 4
Using intValue() method
The Double wrapper class of the double primitive type also has a method called intValue() which converts the double value into an int value.
public class Codekru {
public static void main(String[] args) {
double d1 = 3.14;
Double d = d1;
int i1 = d.intValue();
System.out.println("i1 value = " + i1);
}
}
Output –
i1 value = 3
Do you know that the intValue() method uses typecasting internally?
Internal implementation of the intValue() method in the Double class
public int intValue() {
return (int)value;
}
Hope you have liked the article. If you have any doubts or concerns, please feel free to write us in comments or mail us at admin@codekru.com.