In the previous article we have discussed Java Program to Convert String to float
In this article we will see how to convert string type to double type.
Program to Convert String to double
Before going into the program, let’s see some examples first of both the types.
Example-1: double type double a = 3.123456789 double b = 3.5E02
Example-2: String type String a = "BtechGeeks"; String b = "B";
Let’s see how to do it.
Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.
Method 1 : Java Program to Convert String to double Using parseDouble() method
String type variable can be converted to double by using parseDouble()
see how it actually works.
Here this method is a wrapper class in Java. This method of the Double class converts the string variables into double.
Approach:
- Take a string value and store it in a string variable
input1
. - Then pass that
input1
variable as parameter toparseDouble()
method which will convert the string into double value and return it. - Store that double value in a variable
output
. - Display the result .
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a integer value through scanner class System.out.print("Enter a string : "); String input1=sc.next(); // converting to Double Double output =Double.parseDouble(input1) ; System.out.println("Converted Double value is : " + output); } }
Output : Enter a String : 6.666 Converted Double value is : 6.666
Method 2 : Java Program to Convert String to double Using valueOf() method
String type variable can be converted to double by using valueOf()
, let’s see how it actually works.
This method returns an object of the Double class. However, the object will be automatically converted into the primitive type.
Approach:
- Take a string value and store it in a string variable
input1
. - Then pass that
input1
variable as parameter tovalueOf()
method which will convert thestring
intodouble
value and return it . - Store that double value in a variable
output
- Display the result .
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a String value through scanner class System.out.print("Enter a string : "); String input1=sc.next(); // converting to Double Double output =Double.valueOf(input1) ; System.out.println("Converted Double value is : " + output); } }
Output : Enter a String : 6.666 Converted Double value is : 6.666
Explore complete java concepts from the Java programming examples and get ready to become a
good programmer and crack the java software developer interview with ease.
Related Java Program: