Java Program to Convert double to int - The Coding Shala

Home >> Java Programs >> Convert double to int

Hey there, welcome back to another post. In this post, we are going to learn how to convert double to int in Java.

Java Program to Convert double to int

The most common ways to convert double to int in Java are below:

  1.  By using type-casting.
  2. By using Double class's intValue() method.
  3. By using Math class's round() method.

Now let's see those methods with examples in Java.

Java Example to Convert double to int by using Type Casting

We can use explicit type casting to convert double to int data type, it will truncate all the digits after the decimal.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void main(String[] args) {
        double d1 = 5.70;

        // type casting
        int num1 = (int) d1;
        System.out.println("double is: " + d1);
        System.out.println("Converted int is: " + num1);
    }
}

Output: 

double is: 5.7
Converted int is: 5

Java Example to Convert double to int using Double.intValue()

We can use the Wrapper class Double to convert double to int data type. First, we need to convert primitive double to Double class's object then we can use the intValue() method.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void main(String[] args) {
        double d1 = 5.70;

        // by using Double.getInt()
        Double dNum = d1;
        int num1 = dNum.intValue();
        System.out.println("double is: " + dNum);
        System.out.println("Converted int is: " + num1);
    }
}

Output: 

double is: 5.7
Converted int is: 5

Java Example to Convert double to int using Math.round() method

When we want to convert the double value to the nearest int number then we need to use the Math class's round() method. In this example, Math.round(double) will return a long data type so we need to type cast to int.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void main(String[] args) {
        double d1 = 5.70;

        // by using Math.round()
        int num1 = (int) Math.round(d1);
        System.out.println("double is: " + d1);
        System.out.println("Converted int is: " + num1);
    }
}

Output: 

double is: 5.7
Converted int is: 6


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala