How to Convert String to double in Java

How to Convert String to double in java

It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from the text field, entered data is received as String, and we need to convert it from String to double. There are three methods to convert String to double:

  • Using Double.parseDouble(String) method
  • Using  Double.valueOf(String) method
  • Using the Constructor of Double class

Remember

  • All characters must be in digits.
  • The number can have a minus (-) sign.

Valid Conversions

  • String str=”23”;
  • String str=”-23.111”;

Invalid Conversions

  • String str=”23.54a”;
  • String str=” a23.90”;
  • String str=”abcd”;
  • String str=””;

If you defines a String as above, All the methods throw NumberFormatException, because it is not a valid conversion. 

Using Double.parseDouble() method

This is the static method of Double class. It returns the double primitive value. The signature of the method is given below.

Where s is the String, we are passing to the method as an argument.

Example

In the following example, str is a variable of type String that number “12.037” as a string. The area is a variable of type double that stores the double value return by the parseDouble() method. Double is a wrapper class. parseDouble() is the static method of Double class and returns a double value. The println statement prints the converted value of the str variable.

Output

Using Double.valueOf(String) method

This is the method of Double wrapper class. It is similar to parseDouble() method. It also returns the double primitive value.  The signature of the method is given below.

Where str is the String, we are passing to the method as an argument.

Example

In the following example, var is a variable of type String that contains number “147.2369” as a String. value is a variable of type double that stores the double value return by the valueOf() method. Double is a wrapper class. valueOf() is the method passing var as an argument and returns a double value. The println statement prints the converted value of the variable var.

Output

Using the Constructor of Double class

Double class has a constructor that parses the String an argument and returns Double object. The signature of the method is given below.

Where s is the String, we are passing to the method as an argument.

Example

In this example, str is a variable of type String having a number “222.555” as a string. The number is a variable of type double that stores the double object return by the Double() constructor. Double is the constructor of Double class parses str as an argument. The println statement prints the converted value of the variable str.

Output