March 26, 2024

How to Convert double to String in Java

This post shows how you can convert double to String in Java.

1. Converting double to String using Double.toString() method

Wrapper class Double in Java has a toString() method that returns a string representation of the passed double argument which can be used to convert double to String in Java.

public class DoubleToString {
	public static void main(String[] args) {
	    double num = 3785.8945d;
	    String str = Double.toString(num);
	    System.out.println("Converted String value = " + str);
	}
}
Output
Converted String value = 3785.8945

2. Convert using String.valueOf() method

String.valueOf(double d)- Returns the string representation of the double argument.

public class DoubleToString {
  public static void main(String[] args) {
    double val = -134.76d;
    String str = String.valueOf(val);
    System.out.println("Converted String value = " + str);
  }
}
Output
Converted String value = -134.76

3. Converting using String concatenation

You can concatenate the double value with an empty string ("") using + operator, that will return the result as a String.

public class DoubleToString {
	public static void main(String[] args) {
	    double val = 26.89;
	    String str = val + "";
	    System.out.println("Type of str is- " + str.getClass().getSimpleName());
	}
}
Output
Type of str is- String

4. Converting using append method of StringBuilder or StringBuffer class

Both StringBuilder and StringBuffer classes have append() method where you can pass double as an argument. The append() method will append the string representation of the double argument to the sequence.

public class DoubleToString {
  public static void main(String[] args) {
    double val = -826.89;
    StringBuilder sb = new StringBuilder();
    sb.append(val);
    System.out.println("Converted String value = " + sb.toString());
  }
}
Output
Converted String value = -826.89

That's all for the topic How to Convert double to String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment