Menu

How to Convert double to String in Java?

How to Convert Java double to String

In Java, we can convert double into a String in the following two ways:

  • by using String.valueOf() method
  • by using Double.toString() method

1. By using String.valueOf() Method

The valueOf() method is a part of String class. It is a static method that converts a double into a String value.

Example 1:

Here the double value passed in the method is converted into a String.

public class StudyTonight
{  
    public static void main(String args[])
    {  
        double n = 500.88;  
        String s=String.valueOf(n); 
        System.out.println("The string value is " +s);
        System.out.println(n+100); //will return 600.88 because + is binary plus operator 
        System.out.println(s+100);//will return 500.88100 because + is string concatenation operator  
    }
}

Output:

The string value is 500.88 600.88 500.88100

2. By using Double.toString() method

The toString() method is a part of Double Class. It is a static method that can also be used to convert double value to String.

Example 2:

Here the double value passed in the method is converted into a String.

public class StudyTonight
{  
    public static void main(String args[])
    {  
        double n = 500.77;  
        String s = Double.toString(n); 
        System.out.println("The string value is " +s);
        System.out.println(n+100); //will return 600 because + is binary plus operator 
        System.out.println(s+100);//will return 500100 because + is string concatenation operator  
    }
}

Output:

The string value is 500.77 600.77 500.77100

Example 3:

Here the double value passed in the method is converted into a String formatted up to a specified number of digits.

import java.text.DecimalFormat;
public class StudyTonight
{  
    public static void main(String args[])
    {  
        double num = 500.88;  
        System.out.println(String.format ("%f", num));
        System.out.println(String.format ("%.9f", num));
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.000000");
        String numberAsString = decimalFormat.format(num);
        System.out.println(numberAsString);
    }
}

Output:

500.880000 500.880000000 500.880000

Example 4:

Here the double value passed in the method is converted into a String using concatenation.

public class StudyTonight
{  
    public static void main(String args[])
    {  
        double num = 500.88;  
        String s = num+""; //concat
        System.out.println(s);
    }
}

Output:

500.88