In this tutorial, we will get to know how to convert Java string to double data type:
We will learn to use the following methods to convert string to double value in Java:
- Double.parseDouble(String)
- Double.valueOf(String)
- DecimalFormat parse()
- new Double(String s)
=> Check ALL Java Tutorials Here
Table of Contents:
Methods To Convert Java String To double
There are certain scenarios where, in our Java program we have to perform some kind of arithmetic operations on a numeric value like calculating the bill, calculating interest on the deposit amount, etc. But the input for this program is available in the text format i.e. Java String data type.
For Example, for calculating grocery bills – the product price and the number of units purchased are coming as an input from the text field of a webpage or a text area of a web page in the text format i.e. Java String data type. In such scenarios, we first have to convert this String to retrieve numbers in Java primitive data type double.
Let’s see the various methods one by one in detail.
#1) Double.parseDouble() Method
parseDouble() method is provided by the class Double. The Double class is called the Wrapper class as it wraps the value of the primitive type double in an object.
Let’s have a look at the method signature below:
public static double parseDouble(String str) throws NumberFormatException
This is a static method on class Double which returns a double data type represented by the specified String.
Here, the ‘str’ parameter is a String containing the double value representation to be parsed and returns the double value represented by the argument.
This method throws an Exception NumberFormatException when the String does not contain a parsable double.
For Example, let us consider a scenario when we want to calculate the price after receiving a discount on the original price of the items.
For this, the input values like the original price of the item and discount are coming from your billing system as text and we want to perform an arithmetic operation on these values to calculate the new price after deducting the discount from the original price.
Let’s see how to use Double.parseDouble() method to parse String value to double in the following sample code:
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert string to double java program * using Double.parseDouble() method * * @author * */ public class StringToDoubleDemo1 { public static void main(String[] args) { // Assign "500.00" to String variable originalPriceStr String originalPriceStr = "50.00D"; // Assign "30" to String variable originalPriceStr String discountStr = "+30.0005d"; System.out.println("originalPriceStr :"+originalPriceStr); System.out.println("discountStr :"+discountStr); // Pass originalPriceStr i.e. String “50.00D” as a parameter to parseDouble() // to convert string 'originalPriceStr' value to double // and assign it to double variable originalPrice double originalPrice = Double.parseDouble(originalPriceStr); // Pass discountStr i.e. String “30.005d” as a parameter to parseDouble() // to convert string 'discountStr' value to double // and assign it to double variable discount double discount = Double.parseDouble(discountStr); System.out.println("Welcome, our original price is : $"+originalPrice+""); System.out.println("We are offering discount :"+discount+"%"); //Calculate new price after discount double newPrice = originalPrice - ((originalPrice*discount)/100); //Print new price after getting discount on the console System.out.println("Enjoy new attractive price after discount: $"+newPrice+""); } }
Here is the program Output:
originalPriceStr :50.00D
discountStr :+30.0005d
Welcome, our original price is : $50.0
We are offering discount :30.0005%
Enjoy new attractive price after discount : $34.99975
Here, String is “50.00D” in which D indicates string as a double value.
String originalPriceStr = "50.00D";
This originalPriceStr i.e. “50.00D” is passed as a parameter to parseDouble() method and the value is assigned to double variable originalPrice.
double originalPrice = Double.parseDouble(originalPriceStr);
parseDouble() method converts String value to double and removes “+” or “-“ and ‘D’,’d’.
Hence, when we print originalPrice on the console:
System.out.println("Welcome, our original price is : $"+originalPrice+"");
The following output will be displayed on the console:
Welcome, our original price is : $50.0
Similarly, for String discountStr = “+30.0005d”; String “+30.0005d” can be converted to double using parseDouble() method as:
double discount = Double.parseDouble(discountStr);
Hence, when we print discount on the console.
System.out.println("We are offering discount :"+discount+"%");
The following output will be displayed on the console:
We are offering discount :30.0005%
Furthermore, arithmetic operations are performed on these numeric values in the program.
#2) Double.valueOf() Method
valueOf() method is provided by the wrapper class Double.
Let’s have a look at the method signature below:
public static Double valueOf(String str) throws NumberFormatException
This static method returns the object of data type Double having the double value which is represented by the specified String str.
Here, the ‘str’ parameter is a String containing the double representation to be parsed and returns the Double value represented by the argument in decimal.
This method throws an Exception NumberFormatException when the String does not contain a numeric value that can be parsed.
Let us try to understand how to use this Double.valueOf() method with the help of the following sample program:
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert string to double java program * using Double.valueOf() method * * @author * */ public class StringToDoubleDemo2 { public static void main(String[] args) { // Assign "1000.0000d" to String variable depositAmountStr String depositAmountStr = "1000.0000d"; // Assign "5.00D" to String variable interestRate String interestRateStr = "+5.00D"; // Assign "2" to String variable yearsStr String yearsStr = "2"; System.out.println("depositAmountStr :"+depositAmountStr); System.out.println("interestRateStr :"+interestRateStr); System.out.println("yearsStr :"+yearsStr); // Pass depositAmountStr i.e.String “1000.0000d” as a parameter to valueOf() // to convert string 'depositAmountStr' value to double // and assign it to double variable depositAmount Double depositAmount = Double.valueOf(depositAmountStr); // Pass interestRateStr i.e.String “5.00D” as a parameter to valueOf() // to convert string 'interestRateStr' value to double // and assign it to double variable discount Double interestRate = Double.valueOf(interestRateStr); // Pass yearsStr i.e.String “2” as a parameter to valueOf() // to convert string 'yearsStr' value to double // and assign it to double variable discount Double years = Double.valueOf(yearsStr); System.out.println("Welcome to ABC Bank. Thanks for depositing : $"+ depositAmount+" with our bank"); System.out.println("Our bank is offering attractive interest rate for 1 year :"+interestRate+"%"); //Calculate interest after 2 years on the deposit amount Double interestEarned = ((depositAmount*interestRate*years)/100); System.out.println("You will be receiving total interest after "+years+" is $"+interestEarned+""); } }
Here is the program Output:
depositAmountStr :1000.0000d
interestRateStr :+5.00D
yearsStr :2
Welcome to ABC Bank. Thanks for depositing : $1000.0 with our bank
Our bank is offering attractive interest rate for 1 year :5.0%
You will be receiving total interest after 2.0 is $100.0
Here, we are assigning values to String variables:
String depositAmountStr = "1000.0000d"; String interestRateStr = "+5.00D"; String yearsStr = "2";
Use the valueOf() method to convert these values to Double as shown below.
Double depositAmount = Double.valueOf(depositAmountStr);
We use the same values for further arithmetic calculation as:
Double interestEarned = ((depositAmount*interestRate*years)/100);
#3) DecimalFormat Parse () Method
For this, we first retrieve the NumberFormat class instance and use the parse() method of the NumberFormat class.
Let us have a look at the method signature below:
public Number parse(String str) throws ParseException
This method parses the specified text. This uses a string from the beginning position and returns the number.
This method throws an Exception ParseException if the String’s beginning is not in a parsable.
Let us see the sample program below. This sample code parses formatted text string containing double value using the parse() method:
package com.softwaretestinghelp; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; /** * This class demonstrates sample code to convert string to double java program * using DecimalFormat parse () method * * @author * */ public class StringToDoubleDemo3 { public static void main(String [] args) throws ParseException { // Assign "5,000,00.00" to String variable pointsString String pointsString = "5,000,00.00"; System.out.println("pointsString :"+pointsString); // Pass pointsString i.e. String “+5,000,00.00” as a parameter to // DecimalFormat.getNumberInstance(). parse() method // to convert string pointsString value to double // and assign it to double variable points NumberFormat num = DecimalFormat.getNumberInstance(); Number pointsNum = num.parse(pointsString); double points = pointsNum.doubleValue(); System.out.println("Congratulations ! You have earned :"+points+" points!"); } }
Here is the program Output:
pointsString :5,000,00.00
Congratulations ! You have earned :500000.0 points!
Here, the formatted text is assigned to the string variable as follows:
String pointsString = "5,000,00.00";
This formatted text “5,000,00.00” is passed as an argument to the num.parse() method.
Before that NumberFormat class instance is created using the DecimalFormat.getNumberInstance() method.
DecimalFormat.getNumberInstance() method. NumberFormat num = DecimalFormat.getNumberInstance(); Number pointsNum = num.parse(pointsString);
So, double value is retrieved by invoking doubleValue () method as shown below.
double points = pointsNum.doubleValue();
#4) New Double() Constructor
One more way of converting Java String to double is using a Double class constructor(String str)
public Double(String str) throws NumberFormatException
This constructor constructs and returns a Double object having the value of double type represented by String specified.
str is a string for conversion to Double
This method throws an exception called NumberFormatException if the String does not have a parsable numeric value.
Let us try to understand how to use this Double (String str) constructor with the help of the following sample program that calculates the area of the circle by converting radius to double from String first.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert string to double java program * using new Double(String str) constructor * * @author * */ public class StringToDoubleDemo4 { public static void main(String[] args) { // Assign "+15.0005d" to String variable radiusStr String radiusStr = "+15.0005d"; System.out.println("radiusStr :"+radiusStr); // Pass radiusStr i.e.String “+15.0005d” as a parameter to new Double() // to convert string radiusStr value to double // and assign it to double variable radius double radius = <strong>new</strong><span style="text-decoration: line-through;"><u>Double</u></span><u>(radiusStr)</u>.doubleValue(); System.out.println("Radius of circle :"+radius+" cm"); //Calculate area of circle double area = (3.14*(radius*radius)); System.out.println("Area of circle :"+area+" cm"); } }
Here is the program Output:
radiusStr :+15.0005d
Radius of circle :15.0005 cm
Area of circle :706.5471007850001 cm
In the above program, radius value of the circle is assigned to String variable:
String radiusStr = "+15.0005d";
To calculate the area of the circle, radius is converted to double value using the Double() constructor which returns Double data type value. Then the doubleValue() method is invoked to retrieve the value of primitive date type double as shown below.
double radius = newDouble(radiusStr).doubleValue();
Note: Double(String str) constructor is deprecated since Java 9.0. That is the reason for which Double has strikethrough in the above statement.
Hence, this way is less preferred now. Thus, we have covered all the methods for converting a Java String to a double Java primitive data type.
Let us have a look at following some of the frequently asked questions about the String to double conversion method.
Frequently Asked Questions
Q #1) Can we convert string to double in Java?
Answer: Yes, in Java, String to double conversion can be done using the following Java class methods:
- Double.parseDouble(String)
- Double.valueOf(String)
- DecimalFormat parse()
- new Double(String s)
Q #2) How do you turn a string into a double?
Answer: Java provides various methods for turning a string into a double.
Given below are the Java class methods:
- Double.parseDouble(String)
- Double.valueOf(String)
- DecimalFormat parse()
- new Double(String s)
Q #3) Is double in Java?
Answer: Yes. Java provides various primitive data types to store numeric values like short, int, double, etc. double is a Java primitive data type for representing a floating-point number. This data type takes 8 bytes for storage having 64-bit floating-point precision. This data type is a common choice for representing decimal values.
Q #4) What is Scanner in Java?
Answer: Java provides java.util.Scanner class to get input from a user. It has various methods to get input in different data types. For Example, nextLine() is used to read the String data type value. To read double data value, it provides the nextDouble() method.
Conclusion
In this tutorial, we saw how to convert String data type to primitive data type double in Java using the following class methods along with simple examples.
- Double.parseDouble(String)
- Double.valueOf(String)
- DecimalFormat parse()
- new Double(String s)
=> Read Through The Easy Java Training Series