Java – Convert String to double
In Java, we can use Double.parseDouble()
to convert a String to double
1. Double.parseDouble()
Example to convert a String 3.142
to an primitive double.
String str = "3.142";
double pi = Double.parseDouble(str);
System.out.println(pi);
Output
3.142
2. Double.valueOf()
Example to convert a String 3.142
to an Double object.
String str = "3.142";
Double pi = Double.valueOf(str);
System.out.println(pi);
Output
3.142
Note
In summary,
In summary,
Double.parseDouble(String)
returns a primitive double; while Double.valueOf(String)
returns a new Double object.
3. NumberFormatException
If the string is not a parsable double, a NumberFormatException
will be thrown.
String str = "120,000";
double salary = Double.parseDouble(str);
System.out.println(salary);
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "120,000"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:549)
at com.mkyong.App1.main(App1.java:9)
To fix it, replace ,
with a .
DecimalFormat df = new DecimalFormat("0.00");
String str = "120,000";
double salary = Double.parseDouble(str.replace(",", "."));
System.out.println(salary);
System.out.println(df.format(salary));
Output
120.0
120.00
4. 12,000,000?
Try NumberFormat
to parse the String and returns back a double.
StringToDouble.java
package com.mkyong;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
public class StringToDouble {
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) throws ParseException {
String str = "12,000,000";
NumberFormat format = NumberFormat.getInstance();
Number parse = format.parse(str);
System.out.println(parse);
double salary = parse.doubleValue();
System.out.println(salary);
System.out.println(df.format(salary));
}
}
Output
12000000
1.2E7
12000000.00
References
About Author
Comments
Subscribe
0 Comments