How to Convert String to double in Java

To convert String to double in Java you can use one of the following options-

  1. Double.parseDouble(String s)– Returns a new double initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable double.
  2. Double.valueOf(String s)– Returns a Double object holding the double value represented by the argument string s. Throws NumberFormatException if the string does not contain a parsable number.

As you can see parseDouble() method returns a double primitive where as valueOf() method returns a Double object.

Java example to convert String to double using Double.parseDouble

Output

For double numbers you can use “d” or “D” (even f or F which denotes double) so a String like this – “145.34d” won’t result in NumberFormatException while converting. But having any other alphabet like “145.34c” will throw exception.

Output

Java example to convert String to double using Double.valueOf

Output

NumberFormatException

While converting string to double in Java NumberFormatException is thrown if an invalid number string is passed for conversion.

Output

That’s all for the topic How to Convert String to double in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

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