Sunday, January 19, 2025
HomeProgrammingConverting Double to Integer in Java

Converting Double to Integer in Java

In Java, you can convert a double to an int using type casting. Here’s how you can do it:

1. Using Type Casting (Explicit Casting)

When you convert a double to an int, the decimal part is truncated (not rounded). This means that the fractional part of the number is discarded.

Example:

public class Main {
    public static void main(String[] args) {
        double doubleValue = 45.67;
        
        // Convert double to int
        int intValue = (int) doubleValue;
        
        System.out.println("Double Value: " + doubleValue); // 45.67
        System.out.println("Integer Value: " + intValue);  // 45
    }
}

Explanation:

  • (int) doubleValue: This is called explicit casting. It converts the double value into an int by truncating the decimal part (removes .67 in this case).
See also  html - How to Get a Tab Character?

Output:

Double Value: 45.67
Integer Value: 45

2. Using Math.round() for Rounding

If you want to round the double to the nearest int (instead of truncating), you can use the Math.round() method. However, Math.round() returns a long, so you will need to cast it to int after rounding.

Example:

public class Main {
    public static void main(String[] args) {
        double doubleValue = 45.67;
        
        // Round double and convert to int
        int intValue = (int) Math.round(doubleValue);
        
        System.out.println("Double Value: " + doubleValue); // 45.67
        System.out.println("Rounded Integer Value: " + intValue);  // 46
    }
}

Explanation:

  • Math.round(doubleValue): This method rounds the double value to the nearest long.
  • (int) Math.round(doubleValue): Cast the rounded long value to int.

Output:

Double Value: 45.67
Rounded Integer Value: 46

3. Using Double.intValue() (for Double object)

If you’re working with Double objects, you can use the intValue() method to convert a Double object to int.

Example:

public class Main {
    public static void main(String[] args) {
        Double doubleValue = 45.67;
        
        // Convert Double to int
        int intValue = doubleValue.intValue();
        
        System.out.println("Double Value: " + doubleValue); // 45.67
        System.out.println("Integer Value: " + intValue);  // 45
    }
}

Output:

Double Value: 45.67
Integer Value: 45

Summary

  • Type casting: (int) doubleValue truncates the decimal.
  • Math.round(): Math.round(doubleValue) rounds the value before converting it to int.
  • Double.intValue(): Used when working with Double objects, to convert the value.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x