PV_PN
PV_PN

Reputation: 103

Exception while trying to convert String value to Double in Java

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

Answers (2)

Nitin Bisht
Nitin Bisht

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:

  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";

Upvotes: 3

Arvind Kumar Avinash
Arvind Kumar Avinash

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

Related Questions