Wednesday, June 30, 2021

How to convert String to double in Java with Example

There are three ways to convert a String to double value in Java, Double.parseDouble() method, Double.valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time. Out of all these methods, the core method is parseDouble() which is specially designed to parse a String containing floating-point value into the Double object. Rest of the methods e.g. valueOf() and constructor uses parseDouble() internally. This method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.

Some of you might be curious and thinking if one method can do the job then why we have three methods for String to Double or double conversion? Well, their purpose is a little bit different and they also provide some other service.

For example, you should be using Double.valueOf() method if you frequently need to convert String to Double because it will likely give better performance by caching frequently used values just like Integer.valueOf() method does. On the other hand, if you use a new Double(String value) constructor then you will always get a new Double object, creating memory pressure for your application.

BTW, in this article, we will not only learn how to convert String to double value but also how to convert Double to String, as it's important to know both sides of a conversion. If you are not looking to convert String to double but to format double values to String, then please check my earlier post, formatting floating-point numbers in Java.




String to Double Conversion in Java

As I said, the following are three main ways to convert a String containing floating-point value into double primitive and Double object. You don't need to worry about which method returns a double primitive value and which method returns Double object because autoboxing will take care of double to Double object conversion automatically. 

BTW, just for your information both parseDouble() and valueOf() returns a double primitive value but new Double() is a constructor it returns a Double object.
  • Double.parseDouble();
  • Double.valueOf();
  • new Double() constructor
In cases where Double object is got autoboxing in Java will take care of converting to double primitive value.

On the reverse side also there are three main ways to convert a double variable to String in Java
  • String concatenation
  • Double.toString() method
  • String.valueOf() method
The first one is very simple, just use the + operator with an empty String and a double variable and you will get an equivalent String literal containing a double value. Just make sure that empty String literal i.e. "" should be the first argument or else + operator will do addition instead of String concatenation.

The second method is mainly for the Double objects, but don't worry even if you have a double value you can leverage autoboxing to first convert it into a Double object and then just call the toString() method on it to get an equivalent String in Java.

The third method uses the valueOf() method of the String class to convert a double value to a String. Since String provides a set of overloaded methods to convert every single data type like boolean, short, char, int, long, float, and double it makes sense to leverage that. Just like other valueOf() methods this can also cache frequently used values along with leveraging String pool.

String to Double to String Conversion in Java



Double to String  - Java Code Example

Enough of theory, now let's see some code in working. In the following example, we will first learn how to convert a String to double and then opposite. We will use the knowledge we gain in the first two paragraphs.

import java.util.Arrays;
import java.util.List;


/**
 * Java Program to convert String to double in Java and vice-versa.
 *
 * @author WINDOWS 8
 */

public class StringToDoubleDemo{
 
 
    public static void main(String args[]){
     
        // let's first start converting String to double
        // there are three ways to convert a String to double in Java
        // parseDouble(), valueOf() and Double() constructor
     
        // Using parseDouble() to parse String to double in Java
        String number = "6.24";
        double d = Double.parseDouble(number);
        System.out.println("String " + number +" is parse to double value : " 
                               + d);
     
     
        // now let's use Double.valueOf() method to get double from String
        String str = "8.23";
        double value = Double.valueOf(str);
        System.out.println("String to double conversion using valueOf : " 
                             + value);
     
     
        // another way is by using Double wrapper class constructor
        // though it will return Double value, autoboxing will convert
        // it to double primitive value
        String floating = "122.44";
        double converted = new Double(floating);
        System.out.println("Double value " + converted + " created from String
                              " + floating );
     
     
        // Now let's do opposite by converting a double value to String in Java
        // again there are three way to get a String value from double
        // by String concatenation, valueOf() and toString() method
     
        // Simplest way to convert a double to String
        double pie = 3.14;
        String parsed = "" + pie;
        System.out.println("Double value : " + pie + " String value : " 
                              + parsed);
     
        // you can also use String.valueOf() to convert double to String
        double myValue = 88.22;
        String doubled = String.valueOf(myValue);
        System.out.println("Double value " + myValue + " converted to String : 
                              " + doubled);
     
        // another way to get String from double is by using Double.toString() 
        // in Java
        Double code = new Double(5543.3);
        String decode = code.toString();
        System.out.println("double : " + code + " String : " + decode);
    }
 
}

That's all about how to convert String to Double in Java. Now you know how you can convert these two frequently used data types into one other. For the sake of best practice, just remember to use Double.valueOf() if you frequently need to convert String to double because it can cache values, it will result in better performance. 

Similarly, when you convert a double to String using String concatenation, make sure to use empty String literal and that too as the first argument otherwise + operator will not perform concatenation.


If you like this tutorial and want to understand more about how to convert one data type to another, you can also check out following Java tutorials :
  • How to convert Map to List in Java (tutorial)
  • How to convert float to String in Java? (tutorial)
  • How to convert Byte array to String in Java? (tutorial)
  • How to convert Double to Long in Java? (tutorial)
  • How to convert String to Int in Java? (example)
  • How to convert Array to String in Java? (tutorial)
  • 5 Ways to convert Java 8 Stream to List? (solution)
  • Best way to Convert Numbers to String in Java? (guide)
  • How to convert binary numbers to decimals in Java? (tutorial)
  • How to convert java.util.Date to java.sql.Date in Java? (tutorial)
  • 5 examples to convert InputStream to String in Java? (tutorial)
  • How to convert Enum to String in Java? (guide)
  • How to convert Character to String in Java? (tutorial)
  • How to convert Array to Set and List in Java? (example)
  • 3 examples to convert Array to ArrayList in Java (tutorial)
  • How to convert SQL date to Util Date in Java? (example)
  • How to convert ArrayList to Set in Java? (tutorial)
  • How to convert Hexadecimal numbers to octal and binary in Java? (tutorial)
  • How to convert lowercase String to uppercase in Java? (example)
  • How to convert String to Enum in Java? (tutorial)
  • How to convert List to Set in Java? (example)

4 comments:

  1. Ty for help! Btw whats your color theme?

    ReplyDelete
    Replies
    1. sorry, don't remember, one of the dark theme from one syntax highlighting website.

      Delete

Feel free to comment, ask questions if you have any doubt.