How to convert a String to double in Java

We can convert a String to a primitive double using the Double.parseDouble method or to a wrapped Double class using the Double.valueOf. When both methods receive an invalid number as argument, a java.lang.NumberFormatException will be thrown.

Convert a String to double using Double.parseDouble

The Double.parseDouble method is used to convert a String to primitive double.

String number = "1234.56";
double convertedNumber = Double.parseDouble(number);
System.out.println("Convert String to double: " + convertedNumber);

String negativeNumber = "-1234.56";
double convertedNegativeNumber = Double.parseDouble(negativeNumber);
System.out.println("Convert negative String to double: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to double: 1234.56
Convert negative String to double: -1234.56

Convert a String to Double using Double.valueOf

The Double.valueOf method is used to convert a String to a wrappedDouble.

String number = "1234.56";
Double convertedNumber = Double.valueOf(number);
System.out.println("Convert String to Double: " + convertedNumber);

String negativeNumber = "-1234.56";
Double convertedNegativeNumber = Double.valueOf(negativeNumber);
System.out.println("Convert negative String to Double: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to Double: 1234.56
Convert negative String to Double: -1234.56

throws java.lang.NumberFormatException

If the String passed in is not a valid Double, an java.lang.NumberFormatException is thrown. In this example "-abc" is not a valid number for type Double.

String invalidNumber = "-abc";
double invalidConvertedNumber = Double.parseDouble(invalidNumber);

The java.lang.NumberFormatException thrown.

Exception in thread "main" java.lang.NumberFormatException: For input string: "-abc"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at com.memorynotfound.ParseDoubleExample.main(ParseDoubleExample.java:16)

References

Download

You may also like...