A double is a primitive data type used to store decimal values, while String represents a sequence of characters. Converting a double to a String is useful when a numeric value needs to be displayed, concatenated with text, or processed as textual data.
StringBuilder.append()can be useful when building larger strings.DecimalFormatprovides more control over numeric formatting
Illustration
Input:
123.456
Output:"123.456"
Different Methods to Convert Double to String
1. Using String.valueOf()
String.valueOf(double) converts the specified double value into its string representation.
class GFG {
public static void main(String[] args) {
double number = 123.456;
String str = String.valueOf(number);
System.out.println("Double: " + number);
System.out.println("String: " + str);
}
}
Output
Double: 123.456 String: 123.456
2. Using Double.toString()
The Double.toString() method returns the string representation of the specified double value.
class GFG {
public static void main(String[] args) {
double number = 123.456;
String str = Double.toString(number);
System.out.println(str);
}
}
Output
123.456
3. Using String.format()
String.format() can convert a double into a formatted string. It is useful when a specific number of decimal places is required.
class GFG {
public static void main(String[] args) {
double number = 123.456;
String str = String.format("%.2f", number);
System.out.println(str);
}
}
Output
123.46
4. Using StringBuilder.append()
The append() method can add a double value to a StringBuilder. Calling toString() then returns the resulting string.
class GFG {
public static void main(String[] args) {
double number = 123.456;
String str = new StringBuilder()
.append(number)
.toString();
System.out.println(str);
}
}
Output
123.456
5. Using DecimalFormat
DecimalFormat can convert and format a double value according to a specified pattern.
import java.text.DecimalFormat;
class GFG {
public static void main(String[] args) {
double number = 123.456;
DecimalFormat df = new DecimalFormat("0.00");
String str = df.format(number);
System.out.println(str);
}
}
Output
123.46