How to convert String to double in Java

  • 14 October 2016
  • ADM

 

How to convert String to double in Java - images/logos/java.jpg

 

To convert a String to double in Java you have two simple options using the static methods from Double class:

  • Double.parseDouble(String s): returns a primitive double value;
  • Double.valueOf(String s): returns an Double object.

Ignoring any of the exceptions that can be thrown, all you need to do to convert a String to double is, use on of this lines of code:

double val1 = Double.parseDouble(value);
double val2 = Double.valueOf(value);

or

Double obj = Double.valueOf(value);

Note: even if the valueOf method is returning an Double object you can use the primitive double because the boxing and unboxing will be done automatically.

Example

package com.admfactory;

public class DoubleConverter {

    public static void main(String[] args) {
	// String value = "2000.02d";
	// String value = "2000.02f";
	String value = "3000.03";
	/** Use the value to see the exceptions */
	// String value = "number";

	try {
	    double val1 = Double.parseDouble(value);
	    System.out.println("val1: " + val1);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    double val2 = Double.valueOf(value);
	    System.out.println("val2: " + val2);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    Double obj = Double.valueOf(value);
	    System.out.println("obj:  " + obj);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}
    }
}

Output

If the value string is a valid double like "1", "2", and so on, it will be converted to a Java primitive double with no problem. The output for this will be:

val1: 3000.03
val2: 3000.03
obj:  3000.03

otherwise, if it fails for any reason, the conversion can throw a NumberFormatException, so to capture and deal with the possible error the code need to be used in try/catch block as shown in the example. The output for this case will be:

java.lang.NumberFormatException: For input string: "number"
 at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
 at java.lang.Double.parseDouble(Double.java:540)
 at com.admfactory.xml.DoubleConverter.main(DoubleConverter.java:13)

Note that values like 2000.02d or 2000.02f are valid double values.

 

References