Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java - convert String to double

1 points
Created by:
170690

In Java, we can convert String to double in couple of different ways.

Short solutions:

``````// solution 1
double num1 = Double.parseDouble("123.45");

// solution 2
Double num2 = Double.valueOf("123.45");

// solution 3
Double num3 = new Double("123.45");``````

## 1. Using Double.parseDouble()

``````public class Example1 {

public static void main(String[] args) {
String str = "123.45";
double num = Double.parseDouble(str);
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

When we use Double.parseDouble() we can use +, - as prefix. Also we can use d or D as postfix. Below we have practical example.

``````public class Example1DifferentPatterns {

public static void main(String[] args) {
// +, - as prefix
System.out.println(Double.parseDouble("+123.45")); // 123.45
System.out.println(Double.parseDouble("-123.45")); // -123.45

// d, D - as postfix
System.out.println(Double.parseDouble("123.45d")); // 123.45
System.out.println(Double.parseDouble("123.45D")); // 123.45

// other examples
System.out.println(Double.parseDouble("+123.45d")); // 123.45
System.out.println(Double.parseDouble("+123.45000111000d")); // 123.45000111
}
}``````

## 2. Using Double.valueOf()

``````public class Example2 {

public static void main(String[] args) {
String str = "123.45";
double num = Double.valueOf(str);
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

## 3. Using constructor - new Double(String s)

``````public class Example3 {

public static void main(String[] args) {
String str = "123.45";
double num = new Double(str);
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

## 4. Using DecimalFormat parse method

``````import java.text.DecimalFormat;
import java.text.ParseException;

public class Example4 {

public static void main(String[] args) throws ParseException {
String str = "123.45";
double num = DecimalFormat.getNumberInstance().parse(str).doubleValue();
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

## 5. Using sun.misc.FloatingDecimal.parseDouble()

``````public class Example5 {

public static void main(String[] args) {
String str = "123.45";
double num = sun.misc.FloatingDecimal.parseDouble(str);
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``
NOTE:
When we look under the hood of:
- `Double.parseDouble("123.45")`
- `Double.valueOf("123.45")`
- `new Double("123.45")`
Then we can see that all of those methods call:
`sun.misc.FloatingDecimal.parseDouble()`

## Reference

Join to our subscribers to be up to date with content, news and offers.