Double.parseDouble () bug in Android

    In search of an occasionally crawling error, I came across an unexpected behavior of the Double.parseDouble () method . Code execution
    Double.parseDouble("4cff9d79-a696-4dfc-89f9-a265ae117257");
    

    did not throw a NumberFormatException. The code worked quite correctly and produced the result - Infinity .

    To say the least, I was surprised. Checked. With dozens of other UUIDs, the method worked correctly, but specifically with this (and some, sometimes coming across others), Android behaved a little mysteriously.

    A test in desktop Java confirmed my hunch - the problem is only in Android.

    What is the matter? Digging around, I found that the problem is in this code, which is executed when parseDouble () is called :

    if (result.e < -1024) {
    	result.zero = true;
    	return result;
    } else if (result.e > 1024) {
    	result.infinity = true;
    	return result;
    }
    


    Double, as you know, also has an exponential notation MeP , where M is the mantissa and P is the exponent (i.e., this entry is similar to M * 10 ^ P ). Android, in (almost) the first place, checks for the presence of an exponent, and when it sees that it is there, and it is larger than 1024, it recognizes the whole number as infinity and stops all checks on this. Using the same code, you can see that if any negative number less than 1024 comes after the letter e, then the number is also considered correct, but equal to zero.

    Really:

    Double.parseDouble("Случайный набор символовe1025"); //Infinity
    Double.parseDouble("Случайный набор символовe-1025"); //0.0
    

    Well, a more realistic option (with UUIDs):

    Double.parseDouble("4cff9d79-a696-4dfc-89f9-a265ae117257"); //Infinity
    Double.parseDouble("4cff9d79-a696-4dfc-89fe-126534117257"); //0.0
    

    In general, using this method when programming for Android is not safe. Use other alternatives.

    PS I looked at the source code for API 17, a bug occurred on a phone with Android 4.4.2.


    UPD According to AlexeiZavjalov , the bug was fixed in AOSP a month ago.

    Also popular now: