Write Java program to Convert String to Double


The program takes a user input string, converts it to a double value using two different methods and prints the resulting double values

Here's a breakdown of the program:

  • First, the program creates a Scanner object to read input from the user.
  • The program prompts the user to enter a number as a string.
  • The user enters a string value.
  • The program stores the string value in a variable named "str".
  • The program creates a double variable named "dou_val" and initializes it to 0.
  • The program uses the Double.valueOf() method to convert the string to a double value and assigns it to the "dou_val" variable.
  • The program prints the resulting double value using the System.out.println() method.
  • The program then uses the Double.parseDouble() method to convert the string to a double value and assigns it to the "dou_val" variable.
  • The program prints the resulting double value using the System.out.println() method.
  • The program ends.

Source Code

import java.util.Scanner;
public class StringToDouble
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		String str;
		System.out.print("Enter the Number : ");
		str = input.next();
		System.out.println("String Value : " + str);
 
		double dou_val = 0;
 
		//doubleValue() Method 1
		dou_val = Double.valueOf(str).doubleValue();
		System.out.println("Double Value Using doubleValue() Method : " + dou_val);
 
		//parseDouble() Method 2
		dou_val = Double.parseDouble(str);
		System.out.println("Double Value Using parseDouble() Method : " + dou_val);
	}
}

Output

Enter the Number : 123.46321566
String Value : 123.46321566
Double Value Using doubleValue() Method : 123.46321566
Double Value Using parseDouble() Method : 123.46321566