Java Program to convert double type variables to int

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java Program to Convert double to int using Typecasting

class Main {
  public static void main(String[] args) {

    // create double variables
    double a = 23.78D;
    double b = 52.11D;

    // convert double into int
    // using typecasting
    int c = (int)a;
    int d = (int)b;

    System.out.println(c);    // 23
    System.out.println(d);    // 52
  }
}

In the above example, we have double type variables a and b. Notice the line,

int c = (int)a;

Here, the higher data type double is converted into a lower data type int. Hence, we need to explicitly use int inside the bracket.

This is called narrowing typecasting. To learn more, visit Java Typecasting.

Note: This process works when the value of double is less than or equal to the maximum value of int (2147483647). Otherwise, there will be a loss in data.


Example 2: Convert double to int using Math.round()

We can also convert the double type variable into int using the Math.round() method. For example,

class Main {
  public static void main(String[] args) {

    // create double variables
    double a = 99.99D;
    double b = 52.11D;

    // convert double into int
    // using typecasting
    int c = (int)Math.round(a);
    int d = (int)Math.round(b);

    System.out.println(c);    // 100
    System.out.println(d);    // 52
  }
}

In the above example, we have created two double variables named a and b. Notice the line,

int c = (int)Math.round(a);

Here,

  • Math.round(a) - converts the decimal value into long value
  • (int) - converts the long value into int using typecasting

The Math.round() method rounds the decimal value to the closest long value. To learn more, visit the Java Math round().


Example 3: Java Program to Convert Double to int

We can also convert an instance of Double class to int using the intValue() method. For example,

class Main {
  public static void main(String[] args) {

    // create an instance of Double
    Double obj = 78.6;

    // convert obj to int
    // using intValue()
    int num = obj.intValue();

    // print the int value
    System.out.println(num);    // 78
  }
}

Here, we have used the intValue() method to convert the object of Double to int.

The Double is a wrapper class in Java. To learn more, visit the Java Wrapper Class.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges