I want to parse an integer accurately, one that has been potentially formatted according to the current locale. If I didn’t parse the integer accurately, I want to know it. So I use:
String string = "1111122222333334444455555";
Locale locale = Locale.getDefault();
NumberFormat numberFormat = NumberFormat.getIntegerInstance(locale);
numberFormat.setParseIntegerOnly();
Number number = numberFormat.parse(string);
Obviously "1111122222333334444455555" represents a big number, bigger than a Long can handle. So NumberFormat gives me… a Double??
I guess I would have expected to receive a BigInteger rather than a Double, especially since I asked for an integer-specific number formatter. But never mind that; the bigger problem is that the double value I get back is 1.1111222223333344E24! This is not equal to 1111122222333334444455555!!
If NumberFormat gives me a parsed value that does not equal that stored in the input string, how do I detect that?
Put another way: “How can I know if the Double value I get back from NumberFormat is exactly equivalent to the integral value represented in the original string?”
The javadocs for
parse()state that it will return a Long if possible, otherwise it will return a Double. So just check that the return value is a Long.“Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), otherwise a Double.”
If it returns a Double, then it is not exactly equivalent to your integral value because a Double cannot accurately represent values at that magnitude. Concrete example: