In this Java program, we will learn to convert a double variables to a string value using several different methods.
Using Double.toString() method
double d = 42.5; String str = Double.toString(d);
This method takes a double as an argument and returns the equivalent String representation.
Using String.valueOf() method
double d = 42.5; String str = String.valueOf(d);
This method also takes a double as an argument and returns a String object that contains the double value represented by the double.
Using DecimalFormat class
double d = 42.5; DecimalFormat df = new DecimalFormat("#.##"); String str = df.format(d);
This method uses the DecimalFormat class to format the double value and returns the string representation. You can use different pattern to format the string representation.
Using String.format() method
double d = 42.5; String str = String.format("%.2f", d);
This method uses the String.format() method to format the double value and returns the string representation.
Java Program to Convert Double to String
public class DoubleToStringExample { public static void main(String[] args) { double d = 42.5; // Using Double.toString() method String str1 = Double.toString(d); System.out.println("Double.toString(): " + str1); // Using String.valueOf() method String str2 = String.valueOf(d); System.out.println("String.valueOf(): " + str2); // Using DecimalFormat class DecimalFormat df = new DecimalFormat("#.##"); String str3 = df.format(d); System.out.println("DecimalFormat: " + str3); // Using String.format() method String str4 = String.format("%.2f", d); System.out.println("String.format(): " + str4); // Using Double.toString() method with the valueOf() method String str5 = String.valueOf(Double.toString(d)); System.out.println("Double.toString() with valueOf(): " + str5); // Using toString() method Double d2 = 42.5; String str6 = d2.toString(); System.out.println("toString(): " + str6); } }Output
Double.toString(): 42.5 String.valueOf(): 42.5 DecimalFormat: 42.5 String.format(): 42.50 Double.toString() with valueOf(): 42.5 toString(): 42.5
This program defines a double variable d with the value 42.5. Then, it demonstrates the use of the Double.toString() method, the String.valueOf() method, the DecimalFormat class, the String.format() method, the Double.toString() method with the valueOf() method and the toString() method for converting the double to a String.