Android parseDouble returns Infinity when it shoul

2019-02-19 01:40发布

问题:

I'm trying to determine if a String represents a Double. I expect the following code to throw a NumberFormatException:

String s = "type1234";

try {
    Double val = Double.parseDouble(s);
} catch (NumberFormatException e) {
    // Handle exception
    e.printStackTrace();
}

Instead, val ends up with Infinity. I ran the code in a standard JVM and it does, indeed, throw NumberFormatException

It looks like Android is ignoring the leading characters 'typ' and then parsing it as e^1234, which is out of Double's range.

Is this the expected behavior? If so, what is a more reliable way to determine if a String can be parsed as a Double?

回答1:

Fastest way to check if a String can be parsed to Double in Java

The answer on this post works on android. I have tested it on ICS.



回答2:

Use a regular expression to validate yourself if you don't trust the framework. Here's an example of one way to do this.

    // You can get much fancier than this to handle all cases, but this should handle most
    String regexDouble = "^-?\\d*(\\.\\d+)?$";
    boolean isDouble = val.matches(regexDouble);