Java Convert String to double With Examples

Java String to double conversion can be done by many ways. Today we will look into some common ways to convert java string to double primitive data type or Double object. Note that since java supports autoboxing, double primitive type and Double object can be used interchangeably without any issues.

Java Convert String to Double

Let’s look at all the different ways to convert string to double in java.

  1. Double.parseDouble()

    We can parse String to double using parseDouble() method. String can start with “-” to denote negative number or “+” to denote positive number. Also any trailing 0s are removed from the double value. We can also have “d” as identifier that string is a double value. This method returns double primitive type. Below code snippet shows how to convert string to double using Double.parseDouble() method.

  2. Double.valueOf()

    This method works almost similar as parseDouble() method, except that it returns Double object. Let’s see how to use this method to convert String to Double object.

  3. new Double(String s)

    We can convert String to Double object through it’s constructor too. Also if we want double primitive type, then we can use doubleValue() method on it. Note that this constructor has been deprecated in Java 9, preferred approach is to use parseDouble() or valueOf() methods.

  4. DecimalFormat parse()

    This is useful to parse formatted string to double. For example, if String is “1,11,111.23d” then we can use DecimalFormat to parse this string to double as:

    Note that parse() method returns instance of Number, so we are calling doubleValue() to get the double primitive type from it. Also this method throw ParseException if the string is not properly formatted.

That’s all for converting string to double in java program.

Reference: Double API Doc

By admin

Leave a Reply