The numeric wrapper classes parse methods all throw an exception of this type

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:

String originalPriceStr = "50.00D";
0

#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:

String originalPriceStr = "50.00D";
1

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 originalPriceStr = "50.00D";
2

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.

String originalPriceStr = "50.00D";
3

So, double value is retrieved by invoking doubleValue () method as shown below.

String originalPriceStr = "50.00D";
4

#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.

String originalPriceStr = "50.00D";
5

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 originalPriceStr = "50.00D";
6

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.

String originalPriceStr = "50.00D";
7

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.

When an exception is thrown by a method that is executing under several layers?

8) When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method.

What is the parent class of all exception in Java?

The Throwable class is the superclass of all Java exceptions and errors. It has two subclasses, Error and Exception but they don't represent checked and unchecked exceptions. The Exception class has a subclass called RuntimeException that contains most unchecked exceptions.

Is a section of code that gracefully responds to exceptions when they are thrown?

Exception handler is a section of code that gracefully responds to exceptions when they are thrown. The process of intercepting and responding to exceptions is called exception handling.

What does it mean to catch an exception?

When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception.