How to Convert String to Double in Java

The double data type, also known as double, is a data type in the JAVA programming language that aids in the storage of high-precision floating-point numbers or data in computer memory. This data type is also known as double because it can hold twice the amount of information and data as a float type. As a result, a double is made up of 8 bytes of data, which is roughly 64 bits in size. The exponent of the double is represented by 11 bits, the sign is represented by 1 bit, and the mantissa of the double is represented by the remaining 52 bits. The range of the double data type is 1.7E-308 to 1.7E+308. So let us start on the tutorial of How to Convert String to Double in Java.

 

What’s The Approach?

 

  • Import the java. util package into the class.

 

  • Now within the main method create a new object of Scanner class, for example, Scanner sc=new Scanner(System. in);

 

  • Use the Scanner class to get the input from the user.

 

  • Use the try and catch to prevent unwanted errors from the user.

 

  • Apply the Double.parseDouble(String_name); to convert the string to double type

 

Also Read: How to Convert Long to String in Java

 

Java Program to convert String to Double in Java

 

/*
 * TechDecode Tutorials
 * 
 * How to Covert String to Double
 * 
 */

import java.util.*;
public class String_to_Double
{
    public static void main(String args[])
    {
        // Creating an object of Scanner class
        Scanner sc=new Scanner (System.in);
        // taking imput from  the user
        System.out.print("Please Enter the String that is to be converted to Double : ");
        String s=sc.nextLine();
        //using try and catch to prevent Wrong inputs
        try
        {
            // converting string to Double
            double num=  Double.parseDouble(s);
            //Printing the Double value
            System.out.println("The converted String to Double is: "+ num);
        }
        catch (NumberFormatException ex){
            //Displaying message for wrong input
            System.out.println("Sorry Wrong Input");

        }
    }
}

Input:- 123

Output:-

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *