String to double

String to double Conversion: Sometimes, we obtain the values in string fomrat in Java. Printing the value is no problem (as long as user gets the same output) as it prints the same value as data type prints. For example, a double value is obtained in string format as in command-line arguments or from TextField's getText() method.

The string value is to be converted into double format to use in calculations as strings (or any objects in Java) cannnot be multiplied or used in any arithmetic operation. To convert, casting does not work as string and double are incompatible for conversion either implicitly or explicitly. It requires extra effort in coding known as "parsing operation". Parsing operation involves the usage of a wrapper class and parseXXX() method. For string to double conversion, it is required Double class and parseDouble() method and explained in the following program.

Program on Conversion from String to double
public class StringToDataType
  public static void main(String args[])
    String str = "10.5";
    System.out.println(str);                  // printing is no problem

    double d1 = Double.parseDouble(str);      // conversion String to double
    System.out.println(d1 * d1);              // using in multiplication

parseDouble() is a method of wrapper class Double which converts string str to double d1. Now d1 can be used in arithmetic operations.

Note: The other way double to string is also possible.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.