Learn Java: Java Q&A: How do I convert a String to a double?
Developer's Daily Java Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Java
Education
Java Q&A Center


Question: How do I convert a String to a double with Java?
Answer:  

Converting a String to a double requires that you first convert the String to a Double object, then convert the Double object to a double data type (Double is an object, while double is a primitive data type).

An example of a simple program that performs this conversion is shown below:

public class s2d {

   public static void main (String[] args) {

      // String s = "fred";    // do this if you want an exception

      String s = "100.00";

      try {
         double d = Double.valueOf(s.trim()).doubleValue();
         System.out.println("double d = " + d);
      } catch (NumberFormatException nfe) {
         System.out.println("NumberFormatException: " + nfe.getMessage());
      }

   }

}

Other notes

  • Double.toString(double d) is used to convert in the other direction, from a double to a String.

 


Read the BLOG

Copyright © 1998-2002 DevDaily Interactive, Inc.
All Rights Reserved.