Double to String example in Java
Lets look at different ways through which we can convert Double value to String in Java. Note that double is a primitive data type whereas Double is an Object. However java supports autoboxing, so they both can be used interchangeably in most of the cases.
1. Using + operator
This is the easiest way to convert double to string in java.
1 2 |
double d = 123.45d; String str = d+""; // str is '123.45' |
2. Double.toString()
We can use Double class toString method to get the string representation of double in decimal points. Below code snippet shows you how to use it to convert double to string in java.
1 2 3 |
double d = 123.45d; String str = Double.toString(d); System.out.println(str); //prints '123.45' |
3. String.valueOf()
1 2 |
double d = 123.456d; String str = String.valueOf(d); // str is '123.456' |
4. new Double(double l)
Double constructor with double argument has been deprecated in Java 9, but you should know it.
1 2 3 4 |
double d = 123.45d; //deprecated from Java 9, use valueOf for better performance String str = new Double(d).toString(); System.out.println(str); |
5. String.format()
We can use Java String format method to convert double to String in our programs.
1 2 3 |
double d = 56.98d; String s = String.format("%f", d); System.out.println(s); //56.980000 |
6. DecimalFormat
We can use DecimalFormat class to convert double to String. We can also get string representation with specified decimal places and rounding of half-up.
1 2 3 4 5 6 7 8 |
double d = 123.454d; String str = DecimalFormat.getNumberInstance().format(d); System.out.println(str); //str is '123.454' //if you don't want formatting str = new DecimalFormat("#.0#").format(d); // rounded to 2 decimal places System.out.println(str); //str is '123.45' str = new DecimalFormat("#.0#").format(123.456); // rounded to 2 decimal places System.out.println(str); //str is '123.46' |
7. StringBuilder and StringBuffer
We can use StringBuilder and StringBuffer append function to convert double to string.
1 2 |
double d = 123.45d; String str = new StringBuilder().append(d).toString(); |