Java

Convert String to double in Java

There are many ways in java through which String to Double conversion can be done. Today we will look into some common ways to convert java String to Double. Note that since java supports autoboxing, double primitive type and Double object can be used interchangeably without any issues.

Convert String to Double

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

1. Convert using Double.parseDouble()

The Double.parseDouble() is a static method that parses the string argument and returns a double value.

Syntax

The parameter s will be converted to a primitive double value. Note that the method will throw a NumberFormatException if the parameter is not a valid double.

Example

Output:
Number is: 111.25

This is the most common and popular solution when you need to convert a String to double. Note that the resulting value is not an instance of the Double class but just a plain primitive double value.

2. Convert using Double.valueOf()

The Double.valueOf() is a static method that will return a Double object holding the value of the specified String.

Syntax

Note that the method will throw a NumberFormatException if the parameter is not a valid double.

Output:
Number is: 111.25

This is the most common method when you wish to convert a String to Double. Note that the resulting value is an instance of the Double class and not a primitive double value.

3. Convert using new Double(String).doubleValue()

Another alternative method is to create an instance of Double class and then invoke it’s doubleValue() method.
Note that this constructor has been deprecated in Java 9
Example

Not a preferred method.

4. Convert using DecimalFormat

The class java.text.DecimalFormat is a class that can be used to convert a number to it’s String representation. It can also be used the other way around – it can parse a String into it’s numerical representation.
Example

Output:
Number is: 111.25

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.