Java Program to Convert Integer to Double

In this Java program, we will learn to convert the integer(int) variables to a string value.In Java, you can convert an int to a double using several different methods.

This program defines an int variable number with the value 25. Then, it demonstrates the use of type casting, the Double.valueOf() method, the Double.parseDouble() method and .doubleValue() method for converting the int to a double.


Using type casting

int number = 25;
double d = (double) number;

This method involves explicitly casting the int to a double. The int value is converted to a double value and stored in the double variable d.


Using the Double.valueOf() method

int number = 25;
double d = Double.valueOf(number);

Double.valueOf() method is similar to the Integer.valueOf() method. It takes an int as an argument and returns a Double object that contains the int value as its double value.


Using Double.parseDouble() method

int number = 25;
double d = Double.parseDouble(Integer.toString(number));

Double.parseDouble() method parse the string as Double, but we need to convert the int to string before using it.


Using Integer.doubleValue() method

Integer number = 25;
double d = number.doubleValue();

It is important to note that, if you are trying to convert a large int to double and that int is too large to be represented as a double, the result will be infinity or negative infinity, depending on the sign of the int.

Also, if the int is too small to be represented as a double, the result will be zero.


Java Program to Convert Integer to Double

public class IntToDoubleExample {
  public static void main(String[] args) {
    int number = 25;

    // Using type casting
    double d1 = (double) number;
    System.out.println("Type casting: " + d1);

    // Using Double.valueOf() method
    double d2 = Double.valueOf(number);
    System.out.println("Double.valueOf(): " + d2);

    // Using Double.parseDouble() method
    double d3 = Double.parseDouble(Integer
            .toString(number));
    System.out.println("Double.parseDouble(): " + d3);

    // Using .doubleValue() method
    Integer number2 = 42;
    double d5 = number2.doubleValue();
    System.out.println(".doubleValue(): " + d5);
  }
}
Output
Type casting: 25.0
Double.valueOf(): 25.0
Double.parseDouble(): 25.0
.doubleValue(): 42.0

This program defines an int variable number with the value 25. Then, it demonstrates the use of type casting, the Double.valueOf() method, the Double.parseDouble() method and .doubleValue() method for converting the int to a double.