Everywhere within my code when I interact with a float value in my database, I always round(); it to 2 decimals in PHP, how come I get values like this: 0.00000305176 within my database sometimes?
-
[`round()`](http://php.net/manual/en/function.round.php) doesn't magically "fix" the floating point numbers. If the value computed by `round()` cannot be represented exactly as a binary floating-point number then you just replaced an approximation with another one. – axiac Mar 12 '16 at 14:55
-
rounding every float simply exacerbates those miniscule errors in precision to significant errors in precision – Mark Baker Mar 12 '16 at 15:04
1 Answers
As far as I know, most, if not all programming languages suffer from this particular issue and the reason is, non-technically put because the machine uses a binary system to work through operations, from what I understand, while we expect a result in a decimal system.
If I understand it correctly the language has no way to precisely represent values such as 0.1, 0.2, or so, because it doesn't understand decimals like we do.
While we have decimal increases on 10s, 100s and 1000, to represent in a power mathematically it is 10^1, 10^2, 10^3, decimals go same way 10^-1, 10^-2, 10^-3, representing 0.1, 0.01 and 0.001.
However in binary the base is 2 not 10, so the same power exponent applies, you'd get 2, 4, 8, and in decimal you'd get 0.5, 0.25, 0.125 , 0.0625. So you see, it is hard for a machine to get an exact 0.1, it can get close though.

- 1,362
- 16
- 30
-
-
That would be a good question, however not the one I know the answer to, and probably has something to do with database, rather then PHP. As for your question "how come you get these results" , I suggest you edit it, to make people give answer as to how to fix it, rather then explain what the problem is. Cheers! – Dellirium Mar 12 '16 at 17:47