📜 ⬆️ ⬇️

Double.parseDouble () bug in Android

Looking for an occasional crawling error, I stumbled upon an unexpected behavior of the Double.parseDouble () method. Code execution
Double.parseDouble("4cff9d79-a696-4dfc-89f9-a265ae117257"); 

did not lead to throwing a NumberFormatException exception. The code quite correctly worked and gave the result - Infinity .

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

Check in Java desktop confirmed my guess - the problem is only in Android.

What is the matter? Having rummaged, I found out that the problem is in this code that is executed when calling parseDouble () :
')
 if (result.e < -1024) { result.zero = true; return result; } else if (result.e > 1024) { result.infinity = true; return result; } 


Double, as is well known, has an exponential record MeP , where M is the mantissa, and P is an exponent (that is, this record is similar to M * 10 ^ P ). Android in the (almost) first place checks for the presence of the exponent, and seeing that it is, and it is more than 1024, recognizes the whole number as infinity and stops all checks on this. By the same code, you can see that if after the letter e there is any negative number less than 1024, then the number is also recognized as 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, it is not safe to use this method when programming for Android. Use other alternatives.

PS I looked for source codes for API 17, the bug arose on phone with Android 4.4.2.


UPD. As reported by AlexeiZavjalov , the bug was fixed in AOSP a month ago.

Source: https://habr.com/ru/post/234193/


All Articles