Reputation: 13
Why does this code provide 853 instead of 854?
(int) ((float) ( "8.54") * 100);
How do I convert (string) "8.54"
into (integer) 854
?
Upvotes: 0
Views: 694
Reputation: 97688
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:
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..
from the string, and convert to int directly, e.g. (int)str_replace(".", "", "8.54"));
Upvotes: 3
Reputation: 29
Try without (int). Like this => (float) ( "8.54") * 100; In this case (int) not necessary.
Upvotes: 0