Reputation: 103
I am getting the below error when trying to convert string to double.
For input string: "1,514,230.15"
Exception:
java.lang.NumberFormatException: For input string: "1,514,230.15"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
This is the line of code I am using
testString = "1,514,230.15"
double d= Double.parseDouble(TestString);
Can someone help me understand what I am doing wrong here?
Upvotes: 0
Views: 1102
Reputation: 5331
Solution 1:
String testString = "1,514,230.15".replace(",", "");
double d = Double.parseDouble(testString);
System.out.println(d);
Or Solution 2:
String input = "1,514,230.15";
NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
double result = numberFormat.parse(input).doubleValue();
System.out.println(result);
Or Solution 3:
String testString = "1514230.15";
double d= Double.parseDouble(testString);
System.out.println(d);
Output:
1514230.15
Explanation:
solution 1
used replace
method to replace all ,
i.e. replace(",", "");
solution 2
used NumberFormat. This class provides the interface for formatting and parsing numbers.solution 3
removed all ,
from testString
i.e. String testString = "1514230.15";
Upvotes: 3
Reputation: 78945
You should use NumberFormat#prase which is specialized for such conversions. Your input string complies with the number format for Locale.US
.
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String input = "1,514,230.15";
NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
double n = numberFormat.parse(input).doubleValue();
System.out.println(n);
}
}
Output:
1514230.15
Upvotes: 3