Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – Converting a String float to an Integer – Wrong value

Why does this code provide 853 instead of 854?

(int) ((float) ( "8.54") * 100);

How do I convert (string) "8.54" into (integer) 854?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First of all, read Is floating point math broken?

8.54 happens to be one of those numbers which can be written precisely in decimal, but not in binary, so (float)"8.54" will actually create a number very very close to, but slightly under, 8.54.

Multiplying that by 100 will create a number very very close to, but slightly under, 854. And casting to int will find the next smallest integer (e.g. 853.9 becomes 853, not 854).

I can think of two solutions:

  • After multiplying by 100, round to the nearest whole number, then convert to integer. Unlike 8.54, 854 itself can be represented precisely in floating point, so round(8.54 * 100) will give a number that is exactly 854, rather than slightly under it. So (int)round((float)"8.54" * 100) will give 854 as an integer.
  • Instead of multiplying by 100, remove the . from the string, and convert to int directly, e.g. (int)str_replace(".", "", "8.54"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading