In this article, we will show you how to convert string to double in java. String to Double conversion in Java is a frequent procedure because both data types are commonly used.
As you can imagine in this example we are going to show all the possible ways of converting
String object to
1. Syntax of the convert operations
First of all, in order to convert a string to double, we can simply create a
Double by setting the specified string to its constructor. Otherwise there are two different operations:
public static Double valueOf(String s): it is a static method that returns a
Doubleobject, which keeps the double value of the specified
public static double parseDouble(String s): this is also a static method that returns a new double, represented by the
Both operations throw
NumberFormatException if the string argument is not a parsable number.
2. Example of String to Double conversion in Java
This is an example of how to convert string to double in java. Create a java class with the name
StringToDoubleClass and paste the following code.
Now lets explain the code above a little bit. Notice that the value of
doubleTest2 is a negative double number with two leading zeros and some extra zeros in the decimal part. As you can see in the output below, both
parseDouble() methods return -10.0 number. Also in the situation of the parameter
dInt, if the specified string represents an integer, the two operations convert it to double again. Of course, if the string can not be parsed to a number,
NumberFormatException is thrown.
Below are the results of the code execution.
Use of Double constructor: 10.0 Use of valueOf with doubleTest: 10.0 Use of valueOf with doubleTest2: -10.0 Use of parseDouble with doubleTest: 10.0 Use of parseDouble with doubleTest2: -10.0 Int to parseDouble: 12.0 NumberFormatException in valueOf, For input string: "jcg"
3. Download the source code
This was an example of string to double in Java.
Download the source code of this example: String to Double Java Example
Last updated on Apr. 22nd, 2020