Skip to Content

Convert Java String to Double example

  1. /*
  2.   Convert Java String to Double example
  3.   This example shows how we can convert String object to a Double object.
  4. */
  5.  
  6. public class JavaStringToDoubleExample {
  7.  
  8.   public static void main(String[] args) {
  9.    
  10.     //We can convert String to Double using one of the following ways.
  11.     //1. Construct Double using constructor.
  12.     Double dObj1 = new Double("100.564");
  13.     System.out.println(dObj1);
  14.    
  15.     //2. Use valueOf method of Double class. This method is static.
  16.     String str1 = "100.476";
  17.     Double dObj2 = Double.valueOf(str1);
  18.     System.out.println(dObj2);
  19.    
  20.     /*
  21.     To convert a String object to a double primitive value parseDouble method
  22.     of Double class. This is a static method.
  23.     */
  24.     String str2 = "76.39";
  25.     double d = Double.parseDouble(str2);
  26.     System.out.println(d);
  27.    
  28.     //Please note that these methods can throw a NumberFormatException if
  29.     //string can not be parsed.
  30.  
  31.   }
  32. }
  33.  
  34. /*
  35. Output of the program would be :
  36. 100.564
  37. 100.476
  38. 76.39
  39. */