Domanda

I want to detect if a given string is a number. It can be int or double

Why is this throwing exception when value = "5,447"

  private boolean isParseDoubleOk(String value) {
    try {
      Double.parseDouble(value);
      return true;
    } catch (NumberFormatException nfe) {
      return false;
    }
  }
È stato utile?

Soluzione

Try

    private boolean isParseDoubleOk(String value) {
    try {
      String str = value.replace(",", "");
      Double.parseDouble(str);
      return true;
    } catch (NumberFormatException nfe) {
      return false;
    }
  }

Altri suggerimenti

Because , comma is String

value = value.replace(",", "");

Replace the comma with a dot:

private boolean isParseDoubleOk(String value)
{
    try
    {
        Double.parseDouble(value.replace(",", "."));
        return true;
    }
        catch (NumberFormatException nfe)
    {
        return false;
    }
}

Remove the comma that's all. If u want to map 5,447 as number, then replace , in the string with empty codes ("") and then check.

Your number is in String format that includes a , comma sign. When you try to convert this string into Double, it surely throws NumberFormatException.

The reason is that Double.parse() accepts a String of number like "12345" not like "12,345".

To avoid this error use following code,

private boolean isParseDoubleOk(String value) 
{
    try {
      value = value.replaceAll ( ",", "" );      // Add this line.
      Double.parseDouble(value.trim());
      return true;
    } catch (NumberFormatException nfe) {
      return false;
    }
}
private boolean isParseDoubleOk(String value) {
    try {
        value = value.replace(",", "");
        Double.parseDouble(value);
        return true;
    } catch (NumberFormatException nfe) {
        return false;
    }
}

Here the link to JLS (Java Language Specification) proving that comma is not a valid decimal point in floating literals.

So you have to replace comma by dot. If you have localized input (in many parts of Europe comma is usual!) then you should either apply direct string processing (replacing comma by dot) or consider java.text.DecimalFormat (or NumberFormat) and then convert any BigDecimal results to double.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top