Reputation: 118
I resolved the issue with the code that i was working, but this is something that bugs me out.
I know that floating point in certain circumnstances just messes up with rounding. I know that php uses types inferences, and there is an automatic cast when you operate aritmetically between strings (i mean, in this particular case, in my example).
Doing the same thing 'by hand in code', result of 160.2 * 50 is 8010, when there is no need for rounding when casting to the integer result. Is just ackward. If anyone knows why this happens, it will enlightment me.
echo "160.2" * "50"; // gives 8010
echo (int) ((float)"160.2" * (int)"50"); // Gives 8009
I solved the issue and my code is working now; this is just for fun. I want to know why and how, step by step php messes up with this. Where is php losing resolution? In what step?
Thanks in advance :)
Upvotes: 3
Views: 3180
Reputation: 29462
Where is php losing resolution? In what step?
When you are casting the result to int. Originally, result is in float, if you increase precision in php settings, you will see that it is something like 8009.9999999999990905052982270718
, casting positive numbers to int is basically same as calling floor()
, that's why it prints 8009
.
Upvotes: 1
Reputation: 46728
PHP represented (float)"160.2"
as the binary equivalent of 160.19999999995343387126...
internally. That would cause the multiplication result to be slight smaller than 8010, which on casting back to int, causes truncation and leads to 8009
160.2 in binary cannot be perfectly represented. It comes out to be a recurring decimal,
10100000.00110011001100110011001100110011...
So you cannot expect it to be accurately represented with float.
Upvotes: 4