Write a Java Program to convert double type variables to int

Java is a programming language that allows developers to perform various operations on different data types, including double and integer types.

While dealing with these data types, there may be a need to convert a double type variable to an integer type variable.

In this tutorial, we will learn how to convert double type variables to int in Java.


To convert a double type variable to int in Java, we can use either of the following two methods:

Using typecasting

Typecasting is a way of converting one data type into another.

In the case of converting a double to an int, we can use typecasting to truncate the decimal portion of the double value and convert it to an int value.

Example:

double d = 10.5;
int i = (int) d;
System.out.println("Double value: " + d);
System.out.println("Integer value: " + i);

Output:

Double value: 10.5
Integer value: 10

Using the Math.floor() method

The Math.floor() method is used to return the largest integer value that is less than or equal to the given double value.

This method can be used to convert a double value to an int value by simply passing the double value as a parameter to the Math.floor() method and then typecasting the result to an int.

Example:

double d = 10.5;
int i = (int) Math.floor(d);
System.out.println("Double value: " + d);
System.out.println("Integer value: " + i);

Output:

Double value: 10.5
Integer value: 10

Conclusion

Converting a double type variable to an int type variable in Java can be achieved using either typecasting or the Math.floor() method.

Typecasting is a simple way of truncating the decimal portion of the double value and converting it to an int value.

The Math.floor() method, on the other hand, returns the largest integer value that is less than or equal to the given double value, which can be used to convert the double value to an int value.