1. Overview

In this tutorial, we’ll cover many ways of converting a String into a double in Java.

2. Double.parseDouble

We can convert a String to a double using the *Double.*parseDouble method:

assertEquals(1.23, Double.parseDouble("1.23"), 0.000001);

3. Double.valueOf

Similarly, we can convert a String into a boxed Double using the Double.valueOf method:

assertEquals(1.23, Double.valueOf("1.23"), 0.000001);

Note that the returned value of Double.valueOf is a boxed Double. Since Java 5, this boxed Double is converted by the compiler to a primitive double where needed.

In general, we should favor Double.parseDouble since it does not require the compiler to perform auto-unboxing.

4. DecimalFormat.parse

When a String representing a double has a more complex format, we can use a DecimalFormat.

For example, we can convert a decimal-based currency value without removing non-numeric symbols:

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

BigDecimal decimal = (BigDecimal) format.parse("-$1,000.57");

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

Similar to the Double.valueOf, the DecimalFormat.parse* method returns a *Number, which we can convert to a primitive double using the doubleValue method. Additionally, we use the setParseBigDecimal method to force DecimalFormat.parse to return a BigDecimal.

Usually, the DecimalFormat is more advanced than we require, thus, we should favor the Double.parseDouble or the Double.valueOf instead.

To learn more about DecimalFormat, please check a practical guide to DecimalFormat.

5. Invalid Conversions

Java provides a uniform interface for handling invalid numeric Strings.

Notably, Double.parseDouble*, Double.valueOf, and DecimalFormat.parse throw a *NullPointerException when we pass null.

Likewise, Double.parseDouble* and Double.valueOf throw a *NumberFormatException when we pass an invalid String that cannot be parsed to a double (such as &).

Lastly, DecimalFormat.parse* throws a *ParseException when we pass an invalid String.

6. Avoiding Deprecrated Conversions

Before Java 9, we could create a boxed Double from a String by instantiating a Double:

new Double("1.23");

As of version 9, Java officially deprecated this method.

7. Conclusion

In conclusion, Java provides us with multiple methods to convert Strings into double values.

In general, we recommend using Double.parseDouble unless a boxed Double is needed.

The source code for this article, including examples, can be found over on GitHub.


« 上一篇: 在Java中修改XML属性
» 下一篇: Java安全基础