Java Program to Convert String to Double

This article shows how to write a Java program to convert string to Double. We can convert string to Double using the parseDouble() function and the Double.valueOf() function.

In this Java program example, we declared two text values and used the Double.parseDouble() function to convert the string values to Double. Note that if you parse the text input, the parseDouble() function will throw an error.

public class StringToDouble {

	public static void main(String[] args) {
		String s1 = "111.456";
		String s2 = "2233.9821";
	
		double d1 = Double.parseDouble(s1);
		double d2 = Double.parseDouble(s2);
		
		System.out.println("Double.parseDouble(s1) result = " + d1);
		System.out.println("Double.parseDouble(s1) result = " + d2);
	}
}
Double.parseDouble(s1) result = 111.456
Double.parseDouble(s1) result = 2233.9821

Java Program to Convert String to Double

This Java example is the same as the above. However, we used the Double.valueOf() function to convert string values to Double data type.

public class StringToDouble {

	public static void main(String[] args) {
		String s3 = "909.876";
		String s4 = "1430.34";
	
		double d3 = Double.valueOf(s3);
		double d4 = Double.valueOf(s4);
		
		System.out.println("Double.valueOf(s3) result  = " + d3);
		System.out.println("Double.valueOf(s4) result  = " + d4);
	}
}
Double.valueOf(s3) result  = 909.876
Double.valueOf(s4) result  = 1430.34

Example 3

This string to the Double program allows the user to enter any text. Next, we used the Double.parseDouble() function and Double.valueOf() function on that user given string value.

import java.util.Scanner;

public class StringToDouble {
	private static Scanner sc;

	public static void main(String[] args) {
		String str;
		
		sc= new Scanner(System.in);

		System.out.println("\n Please Enter any double Value :  ");
		str = sc.nextLine();
		
		double d5 = Double.parseDouble(str);
		double d6 = Double.valueOf(str);
		
		System.out.println("Double.parseDouble(s1) result = " + d5);
		System.out.println("Double.valueOf(s3) result     = " + d6);
	}
}
Java Program to Convert String to Double