Home Java Convert String to Double in Java

Convert String to Double in Java

It is commonly used when handling mathematical operations on a double number string. The entered data is received as a string whenever we retrieve data from a textfield or textarea. We must convert the string to double if the input data is double.

The aim is to transform a String into a Double in Java.

This tutorial shall go over how to convert a String to a Double in Java. You can convert a String to double in three different methods.

  • Using Double.parseDouble(String) method
  • Convert String to Double in Java using Double.valueOf(String)
  • Java Convert String to double using the constructor of Double class – The constructor Double(String) is deprecated since Java version 9
  • DecimalFormat parse()

Convert String to Double in Java examples

Input: String = "1532.75"
Output: 1532.75
  
Input: String = "41560.49"
Output: 41560.49

To complete the objective, we can use a variety of approaches:

Using Double.parseDouble()

The method Double.parseDouble() is used to do this. In addition, the static function of the Double class is parseDouble(). This function returns the double equivalent of the supplied string argument. If the string str provided is null, this method will throw NullPointerException, and if the string format is invalid, it will throw NumberFormatException. For example, if the given string is “6042.80ab,” this method will throw a NumberFormatException.

The following is the signature of the parseDouble() method:

The syntax is as follows:

double str1 = Double.parseDouble(str);

or

public static double parseDouble(str) throws NumberFormatException

This procedure throws an Exception. When the String does not include a parsable double, a NumberFormatException is thrown.

Let’s look at some simple java code to convert a string to a double.

double d=Double.parseDouble("9805.65");

Example 1: using Double.parseDouble()

public class StringToDoubleExample{  
  public static void main(String args[]){  
  String s="23.6";  
  double d=Double.parseDouble("23.6");  
  System.out.println(d);  
  }
}  

Example 2: using Double.parseDouble()

// program for converting a String to Double in Java
// using parseDouble()

public class Codeunderscored {

	// main method
	public static void main(String args[])
	{

		// create a String
		String strVar = "2030.50194";

		// convert into Double
		double strOneVar = Double.parseDouble(strVar);

		// print String as Double
		System.out.println(strOneVar);
	}
}

Example 3: Program for converting a String to double using parseDouble(String)

public class JavaParseDouble{
   public static void main(String args[]){

	String strVal = "5021.1850";

	/* Convert String to double using
	 * parseDouble(String) method of Double
	 * wrapper class
	 */
	double dNumber = Double.parseDouble(strVal);
		
	//displaying the value of variable  dNumber
	System.out.println(dNumber);
   }
}

Consider the following scenario: we want to compute the pricing after receiving a discount on the item’s initial price. The input parameters are such that the item’s original price and discount come from your billing system as text. We want to conduct an arithmetic operation on these numbers to determine the new price after subtracting the discount from the original price.

In the following example code, we’ll learn how to utilize the Double.parseDouble() method to convert a String value to a double:

package com.codeunderscored;
 
/**
 * This class is a demonstration of sample code for converting the String to a double in the java program
 * using Double.parseDouble() method
 *
 * @codeunderscored
 *
 */
 
public class StringToDoubleCalculateDiscount {
     
    public static void main(String[] args) {
         
    // Assign "2250.00" to String variable originalPriceStr
    String originalPriceStrVar = "150.00D";
    // Assigning "50" to String variable originalPriceStrVar
    String discountStrVar = "+50.0005d";
         
    System.out.println("originalPriceStrVar :"+originalPriceStrVar);
    System.out.println("discountStrVar :"+discountStrVar);
         
      // Pass originalPriceStrVar i.e. String "50.00D" as a parameter to parseDouble()
    // to convert string 'originalPriceStrVar' value to double
    // and assign it to double variable originalPriceVar

    double originalPriceVal = Double.parseDouble(originalPriceStr);

    // Pass discountStrVar i.e. String "50.005d" as a parameter to parseDouble()
    // to convert string 'discountStrVar' value to double
    // and assign it to double variable discount
       
    double discountVal = Double.parseDouble(discountStrVar);
         
    System.out.println("Welcome, the item original price is : $"+originalPriceVal+"");
    System.out.println("We are offering the following discount :"+discountVal+"%");
         
    //Calculate new price after discount
    double newPriceVal =   originalPriceVal - ((originalPriceVal*discountVal)/100);
             
    //Printing of the new price after getting the discount on the console
     System.out.println("Enjoy new attractive price after discount: $"+newPriceVal+"");
                 
   }    
}

Using Double.valueOf()

The valueOf() method of the Double wrapper class in Java works the same way as the parseDouble() method in the previous Java example.

The syntax is as follows:

double str1 = Double.valueOf(str);
String strVar = "5021.1850";

double dNumber = Double.valueOf(strVar);

After conversion, the value of dNumber would be 5021.1850.

Let’s look at a complete conversion example utilizing the Double.valueOf(String) function.

Example 1: Program for converting a String to double using valueOf(String)

// Program for Converting  a String to Double in Java
// using parseDouble()

public class Codeunderscored {

	// main method
	public static void main(String args[])
	{

		// create a String
		String strVar = "5021.1850";

		// convert into Double
		double strOneVar = Double.valueOf(strVar);

		// print String as Double
		System.out.println(strOneVar);
	}
}

Example 2: Program for converting a String to double using valueOf(String)

public class JavaValueOf{
   public static void main(String args[]){
	String strVar = "5021.1850";

	/* Convert String to double using
	 * valueOf(String) method of Double
	 * wrapper class
	 */
	double dNumber = Double.valueOf(strVar);
		
	//displaying the value of variable  dNumber
	System.out.println(dNumber);
   }
}

Example 3: Program for converting a String to double using valueOf(String)

package com.codeunderscored;
 
/**
 * This class has sample code responsible for converting the String to double in Java
 * using Double.valueOf() method
 *
 * @author
 *
 */
 
public class StringToDoubleValueOf
     
    public static void main(String[] args) {
         
        // Assign "1000.0000d" to String variable depositAmountStr
        String depositAmountStrVal = "1000.0000d";
        // Assign "5.00D" to String variable interestRate
        String interestRateStrVal = "+5.00D";
        // Assign "2" to String variable yearsStrVal
        String yearsStrVal = "2";
         
        System.out.println("The deposit amount string value :"+depositAmountStrVal);
        System.out.println("The interest rate string :"+interestRateStrVal);
        System.out.println("Number of years string value :"+yearsStrVal);
         
      // Pass depositAmountStrVal i.e.String "1000.0000d" as a parameter to valueOf()
        // to convert string 'depositAmountStrVal' value to double
        // and assign it to double variable depositAmount

        Double depositAmountVal = Double.valueOf(depositAmountStrVal);

    // Pass interestRateStrVal i.e.String "5.00D" as a parameter to valueOf()
        // to convert string 'interestRateStrVal' value to double
        // and assign it to double variable discount        
        Double interestRateVal = Double.valueOf(interestRateStrVal);

        // Pass yearsStrVal i.e.String "2" as a parameter to valueOf()

        // to convert string 'yearsStrVal' value to double
        // and assign it to double variable discount        
        Double yearsVal = Double.valueOf(yearsStrVal);    
         
        System.out.println("Welcome to Code Sacco. Thanks for depositing : $"+
        depositAmountVal+" with our bank");
        System.out.println("Our bank is offering attractive interest rate for       1 year :"+interestRateVal+"%");
     
        // interest calculation  after two years on the deposit amount
        Double interestEarnedVal = ((depositAmountVal*interestRateVal*yearsVal)/100);   
 
        System.out.println("You will be receiving total interest after "+yearsVal+" is $"+interestEarnedVal+"");      
             
    }   
}

Using constructor of Double class

Since Java version 9, the constructor Double(String) has been deprecated. The constructor of the Double class parses the String argument that we send in and produces an equivalent double value.

String strVar = "5021.1850";
double numVar = new Double(strVar);

The syntax is as follows.

Double str1 = new Double(str);

or

public Double(String s) throws NumberFormatException

We can use this constructor to build a new Double-object by giving the String we want to convert.

Example 1: Java Program for converting a String to double using the constructor of Double class

public class DoubleClassExample{
   public static void main(String args[]){
       String strVal ="5021.1850";
       double numVar = new Double(strVal);
       System.out.println(numVar);
   }
}

Example 2: Java Program for converting a String to double using the constructor of Double class

// Program for Converting a String to Double in Java
// using parseDouble()

public class Codeunderscored {

	// main method
	public static void main(String args[])
	{

		// create a String
		String strVal = "2030.50194";

		// convert into Double
		Double strOneVar = new Double(strVal);

		// print String as Double
		System.out.println(strOneVar);
	}
}

DecimalFormat parse()

We can use a DecimalFormat when a String expressing a double has a more complicated format. You can use it to convert a formatted string to a double. For instance, if String is “8,11,666.43d,” we may use DecimalFormat to convert this String to:

String strVar = "8,11,666.43d";
try {
	double dNumber = DecimalFormat.getNumberInstance().parse(strVar).doubleValue();
	System.out.println(dNumber); //811666.48
} catch (ParseException e) {
	e.printStackTrace();
}

Because the parse() method produces a Number instance, we must use doubleValue() to obtain the double primitive type. If the String is not formatted correctly, this function will throw a ParseException. We can convert a decimal-based monetary value without eliminating non-numeric symbols in the following way:

DecimalFormat decimalFormat = new DecimalFormat("\u00A4#,##0.00");
decimalFormat.setParseBigDecimal(true);

BigDecimal decimal = (BigDecimal) decimalFormat.parse("-$9,450.85");

assertEquals(-9450.85, decimal.doubleValue(), 0.000001);

The DecimalFormat.parse method, like Double.valueOf, produces a number, which we may convert to a basic double using the doubleValue method. The setParseBigDecimal method is also used to force DecimalFormat.parse to return a BigDecimal.

The DecimalFormat is usually more complicated than we need. Therefore, we should use the Double instead. Instead, use parseDouble or Double.valueOf. This method parses the text that is passed to it. It returns the number using a string from the beginning position.

This procedure throws an Exception. If the String’s beginning is not in a parsable format, a ParseException is thrown. Using the parse() method, this sample code parses a structured text string containing a double value:

package com.codeunderscored;
 
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
 
/**
 * This class has sample code for the conversion of String to double in Java
 * using DecimalFormat parse () method
 *
 * @author
 *
 */
 
public class StringToDoubleDecimalFormat {
     
// this is the main method 
    public static void main(String [] args) throws ParseException {     
        // Assign "4,380,90.50" to String variable pointsString
        String pointsStringVal = "4,380,90.50";
         
        System.out.println("The points string value is:"+pointsStringVal);
         
        // Pass pointsString i.e. String "+4,380,90.50" as a parameter to
        // DecimalFormat.getNumberInstance().parse() method        
        // to convert string pointsString value to double
        // and assign it to double variable points

        NumberFormat numFormat = DecimalFormat.getNumberInstance();
        Number pointsNumber = numFormat.parse(pointsString);     
        double pointsCount = pointsNumber.doubleValue();
         
        System.out.println("Well Done ! You have earned :"+pointsCount+" points!");    
             
    }   
}

Conversions that are not valid

For incorrect numeric Strings, Java provides a standardized interface. Double.parseDouble, Double.valueOf, and DecimalFormat are a few examples. When we supply null to parse, we get a NullPointerException. Similarly, Double.parseDouble and Double.parseDouble.parseDouble.parseDouble.

When we supply an invalid String that can’t be processed to a double, valueOf throws a NumberFormatException (such as &). Finally, when we provide an invalid String to DecimalFormat.parse, it raises a ParseException.

Conclusion

There are several methods for converting a Java String to a double. Today, we’ve looked at some of the most common methods for converting a Java string to a double primitive data type or a Double-object. Because Java allows autoboxing, you can interchangeably use the double primitive type and the double-object.

Overall, Java gives us various ways to convert Strings to double numbers. In general, we advise you to use Double. Unless a boxed Double is required, use parseDouble.

You may also like

Leave a Comment