Java: Converting double to int

Comments · 2 Views

A double stores decimal values, but sometimes, an integer is required. This is common in sc

In java double to int, and often, you may need to convert one type to another. One such frequent operation is converting a double to an int. Since double is a floating-point type and int is an integer type, the conversion process may involve rounding or truncation of decimal values. This article will explore different ways to perform this conversion and discuss their implications.

Why Convert double to int?

When dealing with index values in arrays (which require integers).

When performing calculations that need whole numbers.

When working with APIs or libraries that only accept integer values.

Methods to Convert double to int in Java

1. Using Type Casting (Explicit Conversion)

One of the simplest ways to convert a double to an int is through explicit type casting:
public class Main {
public static void main(String[] args) {
double num = 9.99;
int result = (int) num;
System.out.println("Converted int value: " + result);
}
}
Output:
Converted int value: 9
This method truncates the decimal part and keeps only the integer portion.

2. Using Math.round()

If rounding to the nearest integer is required, use Math.round():
public class Main {
public static void main(String[] args) {
double num = 9.99;
int result = (int) Math.round(num);
System.out.println("Rounded int value: " + result);
}
}
Output:
This method rounds the value to the nearest whole number before converting it.

3. Using Math.floor() and Math.ceil()

For specific rounding behaviors, Math.floor() and Math.ceil() can be used:

Math.floor(double) rounds down to the nearest integer.

Math.ceil(double) rounds up to the nearest integer.

Example:
public class Main {
public static void main(String[] args) {
Double num = 9.99;
int result = num.intValue();
System.out.println("Converted int value: " + result);
}
}
Conclusion

Choosing the right conversion method depends on the requirement:

Use type casting ((int) doubleValue) for truncation.

Use Math.round() for rounding to the nearest integer.

Use Math.floor() or Math.ceil() for specific rounding behavior.

Use Double.intValue() for object-oriented conversion.

Comments