Monday, August 9, 2021

How to Convert String to Double in Java Program with Example

Many scenarios come in day-to-day Java programming when we need to convert a Double value to String or vice versa. In my earlier article, we have seen how to convert String to Integer and in this article, we will first see how to convert double to String and the later opposite of that from String to double. One important thing to note is Autoboxing which automatically converts primitive type to Object type and is only available from Java 5 onwards. This conversion example assumes the code is running above Java 5 version and actually tested in JDK 1.6, which makes it unable to pass Double-object when the method is expecting double primitive value likeString.valueOf(double d) which expect a double value.

In case, you want to use these examples of String to float prior to Java 5 you probably want to change a bit and use intValue(), doubleValue() method to convert primitive from Object type.


Converting String to Double in Java -  Example

There are at least three ways to convert a String, representing double value, into a Double Object. There could be more ways to do the same, please let us know if you know any other method of conversion which is not listed here.

1) The first way of converting a String to a Double has just created a new Double object. Double has a constructor which expects a String value and it returns a Double object with the same value.

String toBeDouble = "200.20";
Double fromString = new Double(toBeDouble);

Beware of NumberFormatException which will occur if the String is not representing a valid Double value.



2) The second way of String to double conversion is by using parseDouble(String str) from Double class. by far this is my preferred method because it's the more readable and standard way of converting a string value to double. here is an example :

Double doubleString = Double.parseDouble(toBeDouble);

Again you need to take care of NumberFormatException which can occur while converting an invalid double string to a double object.


3) A third way to change String into Double is by using the Double.valueOf(String str) method. Just pass your double string into this method and it will convert to an equivalent Double value.

Double doubleStr = Double.valueOf(toBeDouble);

This method can also throw NumberFormatException if String is null or not convertible to double. though Whitespace is ignored by Java.


convert double to String to double in Java



Converting Double to String in Java - Examples

As with the above examples, there are multiple ways to convert a Double object into a String. In this example of converting double to String, we will see at least four ways of doing the same. this is rather much easier than the opposite.

1) The first way to convert Double to string is using the concatenation operator "+" which produce a new string. This is by far the simplest way of converting a double object to a string.

Double toBeString = 400.40;
String fromDouble = "" + toBeString;


2) The second way of double to String conversion is by using the String.valueOf(double d) method, which takes a double value as an argument and returns it in a form of String literal. here is an example of converting double to String using the valueOf() method.

String strDouble = String.valueOf(toBeString);


3) A third way to convert double into String is by using the toString() method of Double Class, which is essentially the same way used in the first way because the concatenation operator internally calls the toString() method of an object to get its string value.

String stringDouble = toBeString.toString();


4) The fourth way is rather more a flexible way of getting String from Double. it uses String.format() method and returns a formatted string so you can control the precision level and get a String up to two decimal points or three decimal points based on your requirement.


 String convertedString = String.format("%.3f", toBeString);
 
This convertedString contains a double value up to 3 decimal points. "f" is used to format floating-point numbers. As you may have noticed we are passing the Double object to methods that are expecting double primitive value and that is only possible due to autoboxing. if you are running below Java 5 use intValue() doubleValue() methods to get value in primitive format.


These are some basic ways to change any String into a Double wrapper Class and vice versa. Please let us know if you are familiar with any other utility or method or doing the same thing with less hassle maybe like overriding equals using EqualsBuilder and HashCodeBuilder.


Some of my other Java articles:

3 comments:

  1. how to convert formatted double e..g up-to 2 decimal point or 3 decimal point to String in Java ? Also large value of double is represented in exponential format, which string that will be returned. What is string representation of Nan or Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY. does double to String conversion method takes care of all double values automatically ?

    ReplyDelete
  2. A=B*((R*(x-c))/(c-1));

    //this returns a very huge number (double) , my aim is to return a double with two decimal places
    but i've failled and therefore decided to use Math.floor()
    ie.return(Math.floor(A));

    // Yet the returned vary comes in exponential for it has too many digits eg 2678765E9
    so then how can i approximate into two decimal places, pass the values in decimal format AND include thousand separator?

    ReplyDelete
  3. Another advantage of using valueOf() to convert String to double or Double is that valueOf() can cache frequently used double value and since Double is an immutable object you can safely reuse object. So best way to convert String to double is by using valueOf() method.

    ReplyDelete