In the post converting String to double in Java we have already seen ways to do that conversion. This post is about doing just the reverse; convert double to string in Java.
Concatenating with an empty String
Easiest way to convert double to a string in Java is to concatenate double with an empty string. That will give you a string value, conversion is handled for you.
public class DoubleToString { public static void main(String[] args) { double num = 78.111167d; String str = num + ""; System.out.println("Value " + str); System.out.println("Type of str " + str.getClass().getSimpleName()); } }
Output
Value 78.111167 Type of str String
Here note that with double value you can use d or D (f or F, for float values).
Converting double to String in Java using valueOf() method
String class has valueOf()
method which is overloaded and those variants take int, float, double, long data types as parameters. Using valueOf(double d)
method you can convert double to String in Java. Method returns string representation of the passed double argument.
public class DoubleToString { public static void main(String[] args) { double num = -67.16789; String str = String.valueOf(num); System.out.println("Value " + str); } }
Output
Value -67.16789
Using toString() method of the wrapper class
Each of the Number subclass (Integer, Float, Double etc.) includes a class method toString(), that will convert its
primitive type to a string. Thus, using Double.toString(double d)
method of the wrapper class Double, you can convert double to String in Java. Method returns a String object representing the passed double value.
public class DoubleToString { public static void main(String[] args) { double num = 124686.9698694d; String str = Double.toString(num); System.out.println("Value " + str); } }
Output
Value 124686.9698694
Using String.format method
- String format(String format, Object... args)- Returns a formatted string using the specified format string and arguments.
Here as a format you can use 'f' which means floating point and the result is formatted as a decimal number.
public class DoubleToString { public static void main(String[] args) { double num = 124686.9698694d; String str = String.format("%.2f", num); System.out.println("Value " + str); } }
Output
Value 124686.97
Here note that .2f is used as format so there will be 2 decimal places. In the signature of the format() method you can see that second argument is a vararg which is of type Object. Still you can pass double primitive data type because of autoboxing.
That's all for this topic Convert double to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment