How do I convert a double to an int in Java?

You can convert a double value to an int using an explicit cast. This removes the fractional part of the number.

This example converts both positive and negative values so you can see how the conversion works.

Source code

public class DoubleToIntExample {
    public static void main(String[] args) {
        double positiveValue = 42.75;
        double negativeValue = -42.75;

        int positiveResult = (int) positiveValue;
        int negativeResult = (int) negativeValue;

        System.out.println("Original positive value: " + positiveValue);
        System.out.println("Converted positive value: " + positiveResult);

        System.out.println("Original negative value: " + negativeValue);
        System.out.println("Converted negative value: " + negativeResult);
    }
}

Explanation

A double can store a fractional value, while an int stores a whole number within its supported range.

To convert a double to an int, place (int) before the value:

int positiveResult = (int) positiveValue;

The cast converts 42.75 to 42. It removes the fractional part instead of rounding to the nearest integer.

For negative numbers, the conversion also removes the fractional part:

int negativeResult = (int) negativeValue;

This converts -42.75 to -42, not -43. For finite values within the int range, the conversion truncates toward zero.

Java requires an explicit cast for this assignment because converting a double to an int can lose information. Without the cast, the following statement would cause a compilation error:

int positiveResult = positiveValue;

Run the example

With JDK 25 or later installed, compile and run the file:

javac DoubleToIntExample.java
java DoubleToIntExample

Output

Original positive value: 42.75
Converted positive value: 42
Original negative value: -42.75
Converted negative value: -42

Special values and limits

An int can store values from -2147483648 to 2147483647. Casting a double does not throw an exception when the value exceeds this range.

Input Result after casting to int
A value above the maximum int value Integer.MAX_VALUE
A value below the minimum int value Integer.MIN_VALUE
Double.POSITIVE_INFINITY Integer.MAX_VALUE
Double.NEGATIVE_INFINITY Integer.MIN_VALUE
Double.NaN 0

Use an explicit cast when you want to discard the fractional part. If you need rounding to the nearest integer, use a rounding method such as Math.round() instead; its double overload returns a long.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.