Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Double.parseDouble()

Converts a string with a decimal number to a double.

Available since: Java 1.2

Syntax

static double parseDouble(String s)

Parameters

ParameterTypeDescription
sStringA string like 3.14, -2, 1e3. Only a dot is accepted as the separator.

Return value

doubleThe number as a double.

Examples

Parsing strings:

void main() {
    IO.println(Double.parseDouble("3.14") * 2);
    IO.println(Double.parseDouble("1e3"));
    IO.println(Double.parseDouble(" 7 "));
}

Output:

6.28
1000.0
7.0

A comma instead of a dot is an error:

void main() {
    try {
        Double.parseDouble("3,14");
    } catch (NumberFormatException e) {
        IO.println(e.getMessage());
    }
}

Output:

For input string: "3,14"

Notes

Unlike Integer.parseInt(), leading and trailing spaces are allowed. The format does not depend on the system language: replace a comma with a dot (s.replace(',', '.')) or parse with NumberFormat. A double stores numbers approximately — use BigDecimal for money.

See also

  • Integer.parseInt() — Converts a string containing an integer to an int.
  • BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.
  • NumberFormat — Formats numbers, money and percentages by the rules of a chosen country.

Related recipes

In the tutorial

  • Type conversion — Automatic widening, explicit (int) casts, turning strings into numbers with Integer.parseInt and numbers into strings.

Thanks for reading!

Donate to the site — we work hard for you.