Converting Double to Int in Java

Comentários · 22 Visualizações

Type casting is the simplest way to convert a double to an int. By explicitly casting, the

In Java, data type conversion is a common requirement, especially when dealing with numerical values. One such conversion is from double to int. This is necessary when we want to remove the decimal portion and work with whole numbers. Java provides multiple ways to achieve this conversion, each with its own characteristics. In this article, we will explore various methods to convert a double to int java.

1. Using Type Casting

public class DoubleToIntExample {
public static void main(String[] args) {
double num = 9.75;
int result = (int) num;
System.out.println("Converted value: " + result);
}
}
Output:
Converted value: 9
Here, the decimal part .75 is removed, and the integer 9 remains.

2. Using Math.round()

If you want to round the number to the nearest integer, use Math.round(). This method returns a long, so you need to cast it to int.
Here, the decimal part .75 is removed, and the integer 9 remains.

2. Using Math.round()

If you want to round the number to the nearest integer, use Math.round(). This method returns a long, so you need to cast it to int.
2. Using Math.round()

If you want to round the number to the nearest integer, use Math.round(). This method returns a long, so you need to cast it to int.

c

Output:

Rounded value: 10

This method rounds 9.75 to 10 instead of truncating it to 9.

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

Math.floor(double a): Rounds down to the nearest integer.

Math.ceil(double a): Rounds up to the nearest integer.
public class FloorCeilExample {
public static void main(String[] args) {
double num = 9.75;
int floorValue = (int) Math.floor(num);
int ceilValue = (int) Math.ceil(num);
System.out.println("Floor value: " + floorValue);
System.out.println("Ceil value: " + ceilValue);
}
}
Output:

Formatted value: 10

This method does not change the variable type but controls the output format.

Conclusion

Converting a double to an int in Java can be done in multiple ways:

Type casting ((int)) truncates the decimal part.

Math.round() rounds to the nearest integer.

Math.floor() and Math.ceil() provide control over rounding direction.

DecimalFormat helps in formatting for display.

 

Comentários