English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, we will learn how to convert a double precision double variable to an integer (int) in Java.
To understand this example, you should understand the followingJava programmingTopic:
class Main { public static void main(String[] args) { //Create a double variable double a = 23.78D; double b = 52.11D; //Convert double to int //Use explicit type conversion int c = (int)a; int d = (int)b; System.out.println(c); // 23 System.out.println(d); // 52 {} {}
In the above example, we have double type variables a and b. Note this line,
int c = (int)a;
In this case, the higher double data type will be converted to the lower int data type. Therefore, we need to explicitly use int in parentheses.
This is calledNarrowing type conversion. For more information, please visitJava Type Conversion.
Note: When the value of double is less than or equal to int(2147483647). This process is effective when the maximum value is reached. Otherwise, there may be a loss of data due to truncation.
We can also use the Math.round() method to convert a double type variable to an int type variable. For example,
class Main { public static void main(String[] args) { //Create a double variable double a = 99.99D; double b = 52.11D; //Convert double to int //Use type conversion int c = (int)Math.round(a); int d = (int)Math.round(b); System.out.println(c); // 100 System.out.println(d); // 52 {} {}
In the above example, we created two double type variables named a and b. Note this line,
int c = (int)Math.round(a);
Here,
Math.round(a) - Convert a decimal value to a long value
(int) - Convert a long value to an int value using type conversion
The Math.round() method rounds a decimal value to the nearest long value. For more information, please visit Java Math round().
We can also use the intValue() method to convert an instance of the Double class to int. For example
class Main { public static void main(String[] args) { //Create an instance of Double Double obj = 78.6; //Convert obj to int //Use intValue() int num = obj.intValue(); //Print int value System.out.println(num); // 78 {} {}
Here, we used the intValue() method to convert a Double object to int.
Here, Double is a Java wrapper class. For more information, please visitJava Wrapper Classes.