Google News
logo
Java Program to convert double type variables to int

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

Program :
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
  }
}
Output :
23
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.

Convert double to int using Math.round() :

We can also convert the double type variable into int using the Math.round() method. For example,
Program :
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
  }
}
Output :
100
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.