TAG | data-types
Found some nice MySQL data types tips how to create a database schema. Valuable information for intermediate and begginer developers to avoid the common database schema design pitfalls.
echo (int) ( (0.1+0.7) * 10 );
What do you think the output would be? Surprisingly it’s 7. Internally in PHP it’s stored as 7.999999. Gladly this problem is described in PHP manual about float precision.
And sadly .. How many developers starting to develop PHP applications read about integers and float? When I started with PHP I thought to myself.. Hey it’s there. It’s simple and it works. What could be wrong with it? And after a while you wake up developing so called “enterprise applications” and you might start banging your head to the wall when you find out your reports are not so accurate as you thought Probably not many developers make their priority to read about integers and floats?
Turns out this is a usual thing. A quote from PHP.net manual:
"It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision."
PHP.net manual suggests developers should use bcmath extension if higher precision is needed. Not only you can not cast floats to integers but you have to be careful comparing floats.
You might never run into this problem. But when you do it may come as an unpleasant surprise trying to find where is that single penny lost..