This article shows how to write a Java Program to Convert Double to String. We can convert Double to string using the traditional String.valueOf(double) function, Double.toString(), and String.format() function.
In this program, we declared two values and used the Java valueOf(d) function to convert the Double values to strings.
public class DoubleToString { public static void main(String[] args) { double d1 = 19.234; double d2 = 211.42; String str1 = String.valueOf(d1); String str2 = String.valueOf(d2); System.out.println("d1 Converted Value = " + str1); System.out.println("d2 Converted Value = " + str2); } }
d1 Converted Value = 19.234
d2 Converted Value = 211.42
Java Program to Convert Double to String
This example is the same as the above. However, we used the toString() function to convert Double values to the string data type.
public class DoubleToString { public static void main(String[] args) { double d1 = 32.14; double d2 = 444.429; String str1 = Double.toString(d1); String str2 = Double.toString(d2); System.out.println("d1 Converted Value = " + str1); System.out.println("d2 Converted Value = " + str2); } }
d1 Converted Value = 32.14
d2 Converted Value = 444.429
In this Double to String example program, we are using the String.format() function with %f format specifier.
public class DoubleToString { public static void main(String[] args) { double d1 = 55.21; double d2 = 666.99352; String str1 = String.format("%.4f", d1); String str2 = String.format("%.2f", d2); System.out.println("Double d1 Converted to String Value = " + str1); System.out.println("Double d2 Converted to String Value = " + str2); } }
Double d1 Converted to String Value = 55.2100
Double d2 Converted to String Value = 666.99
This program allows users to enter values. Next, we used all three functions String.valueOf(d), Double.toString(), and String.format() on that user given Double value.
import java.util.Scanner; public class DoubleToString { private static Scanner sc; public static void main(String[] args) { double dd; sc= new Scanner(System.in); System.out.println("\n Please Enter any Double Value : "); dd = sc.nextDouble(); String str1 = String.valueOf(dd); String str2 = Double.toString(dd); String str3 = String.format("%.2f", dd); System.out.println("Double dd Converted to String Value = " + str1); System.out.println("Double dd Converted to String Value = " + str2); System.out.println("Double dd Converted to String Value = " + str3); } }