In Java, converting a double value to its equivalent String representation is a common operation, especially when dealing with data manipulation and output formatting. Java provides various methods to convert a double to a String. In this blog post, we will explore different techniques with examples.
1. Using Double.toString() Method
The Double.toString() method is the simplest way to convert a double value to its String representation. It returns a String that contains the decimal representation of the double value.
Example:
public class DoubleToStringExample {
public static void main(String[] args) {
double doubleValue = 123.45;
String stringValue = Double.toString(doubleValue);
System.out.println("Double Value: " + doubleValue);
System.out.println("String Value: " + stringValue);
}
}
Output:
Double Value: 123.45
String Value: 123.45
2. Using String.format() Method
Similar to converting a float, the String.format() method can be used to create a formatted String representation of a double value with desired precision.
Example:
public class DoubleToStringExample {
public static void main(String[] args) {
double doubleValue = 67.89678;
String stringValue = String.format("%.2f", doubleValue);
System.out.println("Double Value: " + doubleValue);
System.out.println("String Value: " + stringValue);
}
}
Output:
Double Value: 67.89678
String Value: 67.90
3. Using DecimalFormat Class
Just like converting a float, you can use the DecimalFormat class to format a double value as a string with more control over the formatting options.
Example:
import java.text.DecimalFormat;
public class DoubleToStringExample {
public static void main(String[] args) {
double doubleValue = 9876.54321;
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
String stringValue = decimalFormat.format(doubleValue);
System.out.println("Double Value: " + doubleValue);
System.out.println("String Value: " + stringValue);
}
}
Output:
Double Value: 9876.54321
String Value: 9,876.54
Conclusion
Converting a double to a String is a common operation in Java, and you have several methods at your disposal. The Double.toString() method is the most straightforward approach, while the String.format() method and DecimalFormat class offer more advanced formatting options.
Related String Conversion Examples
- Java Convert Integer to String Example
- Java Convert Float to String Example
- Java Convert Double to String Example
- Java Convert Short to String Example
- Java Convert Long to String Example
- Java Convert Character to String Example
- Java Convert Byte to String Example
- Java Convert Boolean to String Example
- Java Convert String To Short Example
- Java Convert String To Long Example
- Java Convert String To Integer Example
- Java Convert String To Float Example
- Java Convert String To Double Example
- Java Convert String To Byte Example
- Java Convert String To Boolean Example
Comments
Post a Comment
Leave Comment