How to convert String to Double or Double to String in java | Double example

Double String example

A string is a sequence of characters enclosed in double-quotes.

Double is the numeric data type for double-precision floating values that holds double primitive types. They have distinct values for different purposes. Occasionally, in our applications, there’s a need to convert a string to double or vice versa in Java.

It’s a fundamental requirement for developers to be familiar with. A Double holds 64-bit numbers, and a double value can have d or D added to it, although it’s not compulsory.

Let’s declare string and double variables

String s=new String("123.45");
String s1="23.45";
Double d=new Double("123.45");
Double d1=123.34D;
Double d2=123.34d;

The string should contain a sequence of characters enclosed in double-quotes. For conversion, the string should consist of valid numeric characters enclosed in double-quotes. If non-numeric characters are present in the string, a NumberFormatException will be thrown.

This post discusses how to perform this conversion.

How to Convert Double to String in Java

There are several ways to convert a Double to a String in Java.

  • Using toString() Method Example

    The Double object has a toString() method that returns the string value of the double object. It also returns the string value of a double primitive value.

    Double d=123.43;
    System.out.println(d.toString()); //outputs 123.43
    System.out.println(Double.toString(d)); //outputs 123.43
  • Using valueOf() Method

    The String class has the following static overloaded method that returns the string value of a double value: public static String valueOf(Object value). The object can be of any type.

    Double doubleValue=87.12;
    System.out.println(String.valueOf(doubleValue)); //outputs 87.12
  • Using DecimalFormat Class The java.text.DecimalFormat class is used to format a numeric value and convert it into a string. A DecimalFormat object is created with the constructor of the format parameter, and the format method is used to return the string value.

    Double d= 4578.536;
    DecimalFormat decimalFormat = new DecimalFormat("#.00");
    String strValue = decimalFormat.format(d);

    output is 4578.54

How to Convert String to Double in Java

There are several ways to convert a String to a Double in Java.

  • Append Empty String

    It is simple to convert to a string. Add or append an empty string using the plus operator (+) to the double value to return it as a string.

    Double doubleValue= 8978.78d;
    String stringValue = "" + doubleValue;

    The output is 8978.78

  • Using String format() Method

    The format() method of a string accepts a value and format and converts the value as per the format. String.format(format, ...object). The format % .4f represents four floating decimals.

    Double doubleValue=234.345;
    String stringValue = String.format("%.4f", doubleValue);

    Output is 234.3450