Skip to main content

Posts

Showing posts from June 19, 2016

Be careful of financial data

PHP suffers from floating point imprecision. This issue also affects a few other languages too. So what is floating point imprecision? Let's take a look at an example: <?php echo (int) ((0.1 + 0.7) * 10); ?> Did you guess 8? I'm sorry, you're wrong. The output is actually 7. So what happened? Let me explain: 1st operation: 0.1 + 0.7 // result is 0.79999999999 2nd operation: 0.79999999 * 10 = 7.999999999 3rd operation: (int) 7.9999999 // result is 7 PHP is also loosely typed. So when you're doing any form of numeric variables, you must be aware of the type. You could potentially strip out 99 cents if you convert from float to integer. Normally, a simple website would not encounter such issues, but when you're dealing with financial data, a wrong figure can literal cause you to lose not just your job. You could potentially get into serious legal problems with your company or your client if you cause them millions.