Convert Double to Int in Java

Mohammad Irfan Mar 24, 2021 Mar 06, 2021
  1. Convert double to int Using Type Casting in Java
  2. Convert double to int Using the round() Method in Java
  3. Convert double to int Using the intValue() Method in Java
Convert Double to Int in Java

This tutorial introduces how to convert double to integer in Java.

The double type is used to store floating-point values, and the integer type is used to store non-decimal values(integer) values. There are several ways to convert double type to an integer, such as type casting, intValue() method of the double class. Let’s see some examples.

Convert double to int Using Type Casting in Java

This is the simplest way to convert double to int in Java. Here, we use type casting to get the integer result. It is nice, but it truncates the actual value. It returns only the integer part and excludes the decimal point. See the example below.

public class SimpleTesting{
    public static void main(String[] args) {
        double d_val = 12.90;
        System.out.println("Value in double: "+ d_val);
        int i_val = (int) d_val;
        System.out.println("Value in int: "+i_val);
    }
}

Output:

Value in double: 12.9
Value in int: 12

Convert double to int Using the round() Method in Java

We can use the round() method of Math to convert double to an integer type. We use the round() method because it rounds off the value into the nearest integer. It helps to reduce data truncation. See the example below.

public class SimpleTesting{
    public static void main(String[] args) {
        double d_val = 12.90;
        System.out.println("Value in double: "+ d_val);
        int i_val = (int) Math.round(d_val);
        System.out.println("Value in int: "+i_val);
    }
}

Output:

Value in double: 12.9
Value in int: 13

As You can see, in the above example, casting returns 12, while in this example, casting returns 13 because the round() method returns a roundoff value.

Convert double to int Using the intValue() Method in Java

The Double, a wrapper class in Java, has a method intValue() that returns an integer from the double value. This is easy because it is a built-in method so that we don’t need to use any other class but use the method to get the result. See the example below.

public class SimpleTesting{
    public static void main(String[] args) {
        Double d_val = 12.90; // store into wrapper
        System.out.println("Value in double: "+ d_val);
        int i_val = d_val.intValue();
        System.out.println("Value in int: "+i_val);
    }
}

Output:

Value in double: 12.9
Value in int: 12

Related Article - Java Double

Related Article - Java Int