Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

How to convert Java String to double

In Java, a String can be converted into a double value by using the Double.parseDouble() method. Also, a String can be converted into a Double object using the Double.valueOf() method.

Whenever a data(numerical) is received from a TextField or a TextArea it is in the form of a String and if we want double type then it is required to be converted into a double before performing any mathematical operation. This is done via parseDouble() method.

1. By Using Double.parseDouble() Method

The parseDouble() method is a part of the Double class. It is a static method and is used to convert a String into a double.

Example 1:

Here, a String value is converted into double type value by using the parseDouble() method. See the example below.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		String s="454.90"; //String Decleration 
		double i = Double.parseDouble(s);  // Double.parseDouble() converts the string into double
		System.out.println(i);  
	}
} 


454.9

2. Buy Using Double.valueOf() Method

The valueOf() method is a part of Double class. This method is used to convert a String into a Double Object.

Example 2:

Here, a String value is converted into a double value by using the valueOf() method.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		try
		{
			String s1 = "500.77"; //String declaration 
			double i1 = Double.valueOf(s1);  // Double.valueOf() method converts a String into Double
			System.out.println(i1);  
			String s2 = "mohit"; //NumberFormatException
			double i2 = Double.valueOf(s2);
			System.out.println(i2);
		}
		catch(Exception e)
		{
			System.out.println("Invalid input");
		}
	}
}


500.77
Invalid input

Example 3:

If we want to convert a value that contains commas then use replaceAll() method to replace that commas and the use parseDouble() method to get double value. Here, a String value is converted into double values taking the commas into consideration.

public class StudyTonight
{  
   public static void main(String args[])
   {  
  
       String s = "4,54,8908.90"; //String Decleration 
 
       //replace all commas if present with no comma
       String s1 = s.replaceAll(",","").trim(); 
       
       // if there are any empty spaces also take it out.          
       String f = s1.replaceAll(" ", ""); 
       
       //now convert the string to double
       double result = Double.parseDouble(f);
       
       System.out.println("Double value is : "+ result);
    }
  
} 


Double value is : 4548908.9