EN
Java - convert String to double
1 points
In Java, we can convert String to double in couple of different ways.
Short solutions:
xxxxxxxxxx
1
// solution 1
2
double num1 = Double.parseDouble("123.45");
3
4
// solution 2
5
Double num2 = Double.valueOf("123.45");
6
7
// solution 3
8
Double num3 = new Double("123.45");
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
String str = "123.45";
5
double num = Double.parseDouble(str);
6
System.out.println(num); // 123.45
7
}
8
}
Output:
xxxxxxxxxx
1
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.
xxxxxxxxxx
1
public class Example1DifferentPatterns {
2
3
public static void main(String[] args) {
4
// +, - as prefix
5
System.out.println(Double.parseDouble("+123.45")); // 123.45
6
System.out.println(Double.parseDouble("-123.45")); // -123.45
7
8
// d, D - as postfix
9
System.out.println(Double.parseDouble("123.45d")); // 123.45
10
System.out.println(Double.parseDouble("123.45D")); // 123.45
11
12
// other examples
13
System.out.println(Double.parseDouble("+123.45d")); // 123.45
14
System.out.println(Double.parseDouble("+123.45000111000d")); // 123.45000111
15
}
16
}
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
String str = "123.45";
5
double num = Double.valueOf(str);
6
System.out.println(num); // 123.45
7
}
8
}
Output:
xxxxxxxxxx
1
123.45
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
String str = "123.45";
5
double num = new Double(str);
6
System.out.println(num); // 123.45
7
}
8
}
Output:
xxxxxxxxxx
1
123.45
xxxxxxxxxx
1
import java.text.DecimalFormat;
2
import java.text.ParseException;
3
4
public class Example4 {
5
6
public static void main(String[] args) throws ParseException {
7
String str = "123.45";
8
double num = DecimalFormat.getNumberInstance().parse(str).doubleValue();
9
System.out.println(num); // 123.45
10
}
11
}
Output:
xxxxxxxxxx
1
123.45
xxxxxxxxxx
1
public class Example5 {
2
3
public static void main(String[] args) {
4
String str = "123.45";
5
double num = sun.misc.FloatingDecimal.parseDouble(str);
6
System.out.println(num); // 123.45
7
}
8
}
Output:
xxxxxxxxxx
1
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()