Home > Software design >  PHP - Converting a String float to an Integer - Wrong value
PHP - Converting a String float to an Integer - Wrong value

Time:06-18

Why does this code provide 853 instead of 854?

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

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

CodePudding user response:

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"));

CodePudding user response:

intval(str_replace(".", "", "8.54"))

CodePudding user response:

Try without (int). Like this => (float) ( "8.54") * 100; In this case (int) not necessary.

  • Related