How to Convert String variables to double in Java Program
Java Strings
- A String object is an instance of the java.lang.String class, which is immutable and final. This means that once a String object is created, its value cannot be changed.
- you can create new strings by concatenating existing strings or by creating a new string that is a substring of an existing string.
- Strings in Java are immutable, which means that once you create a string object, its value cannot be changed.
- You must be familiar with following topics to understand the correspond example Such as: Java Strings, Java Data Types.
Steps to convert string variables to double
- Here are the steps to convert string variables to double in Java:, You can follow these steps:
Store the string representation of a number in a String variable.
Use the Double.parseDouble() method to convert the string to a double. The method takes the string representation of a number as its argument and returns the equivalent double value.
Store the result of the Double.parseDouble() method in a double variable.
If the string passed to Double.parseDouble() cannot be successfully parsed into a double, a NumberFormatException will be thrown.
To handle this exception, you can wrap the call to Double.parseDouble() in a try-catch block.
Let’s look at a Java Program to convert string variables to double in Java to perform certain operations.
Example 1: Java Program to convert string variables to double
public class Main { public static void main(String[] args) { String numberAsString = "1234.56"; double numberAsDouble = Double.parseDouble(numberAsString); System.out.println("The number as a double: " + numberAsDouble); } }
Output
The number as a double: 1234.56
Example 2 : Java Program to convert string variables to double
public class Main { public static void main(String[] args) { String numberAsString = "7654.23"; double numberAsDouble = 0.0; try { numberAsDouble = Double.parseDouble(numberAsString); } catch (NumberFormatException e) { System.out.println("Invalid number format."); return; } System.out.println("The number as a double: " + numberAsDouble); } }
Output
The number as a double: 7654.23
Example 3: Java Program to convert string variables to double
public class Main{ public static void main(String args[]){ String str = "809.989"; /* Convert String to double using * parseDouble(String) method of Double * wrapper class */ double dnum = Double.parseDouble(str); //displaying the value of variable dnum System.out.println(dnum); } }
Output
809.989
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment