0

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?

2
  • You can't have commas if you're directly doing Double.parseDouble, since you don't put commas in doubles in Java source code either Commented Jun 12, 2020 at 19:44
  • Possibly related: How to change the decimal separator of DecimalFormat from comma to dot/point? (then you can use those formats like df.parse(stringRepresentingFormattedDouble).doubleValue()). Commented Jun 12, 2020 at 20:07

2 Answers 2

3

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:

  1. In solution 1 used replace method to replace all , i.e. replace(",", "");
  2. In solution 2 used NumberFormat. This class provides the interface for formatting and parsing numbers.
  3. In solution 3 removed all , from testString i.e. String testString = "1514230.15";
Sign up to request clarification or add additional context in comments.

2 Comments

It is worth explaining why NumberFormat.parse is different from Double.parseDouble: NumberFormat is intended for human readable numbers as they would be presented to end users, like the string in the original question; Double.parseDouble is intended for code formatted numbers, that is, numeric values as they would appear in Java code.
Moreover, you stealthily copied my solution and put that as one of your options. Whenever you copy someone's solution, do it with citation.
3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.