Java Program to convert double type variables to string

In this tutorial, we will learn to convert double variables into the string in Java.

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


Example 1: Java Program to Convert double to string using valueOf()

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

    // create double variable
    double num1 = 36.33;
    double num2 = 99.99;

    // convert double to string
    // using valueOf()
    String str1 = String.valueOf(num1);
    String str2 = String.valueOf(num2);

    // print string variables
    System.out.println(str1);    // 36.33
    System.out.println(str2);    // 99.99
  }
}

In the above example, we have used the valueOf() method of the String class to convert the double variables into strings.

Note: This is the most preferred way of converting double variables to string in Java.


Example 2: Java Program to Convert double to string using toString()

We can also convert the double variables into strings using the toString() method of the Double class. For example,

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

    // create double variables
    double num1 = 4.76;
    double num2 = 786.56;

    // convert double to string
    // using toString()
    String str1 = Double.toString(num1);
    String str2 = Double.toString(num2);

    // print string variables
    System.out.println(str1);    // 4.76
    System.out.println(str2);    // 786.56
  }
}

Here, we have used the toString() method of the Double class to convert the double variables into a string.

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


Example 3: Java Program to Convert double to String using + Operator

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

    // create double variables
    double num1 = 347.6D;
    double num2 = 86.56D;

    // convert double to string
    // using + sign
    String str1 = "" + num1;
    String str2 = "" + num2;

    // print string variables
    System.out.println(str1);    // 347.6
    System.out.println(str2);    // 86.56
  }
}

Notice the line,

String str1 = "" + num1;

Here, we are using the string concatenation operation to convert a double variable into the string. To learn more, visit Java String concatenation.


Example 4: Java Program to Convert double to String using format()

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

    // create a double variable
    double num = 99.99;

    // convert double to string using format()
    String str = String.format("%f", num);

    System.out.println(str);    // 99.990000
  }
}

Here, we have used the format() method to format the specified double variable into a string. To learn more about formatting string, visit Java String format().

Did you find this article helpful?