Float to numeric data type conversion bug in php

Today i saw surpring bug in php on data type conversion. We know php is loosely typed lagnuage , that we can convert a datatype to another datatype unlike C, Java. I tried to convert a float value to integer value but it outputs a wrong result…

I wonder why it happens. The code is below

echo (int) ((0.7+0.1)*10);

It’s expected to show 8 but it shows 7.  It’s hard to find the problem. Then i googled this problem and found, the result of this simple arithmetic
expression is stored internally as 7.999999 instead of 8; when the value is converted to int, PHP simply truncates away the fractional part, resulting in a rather significant error (12.5%, to be exact). So experts suggested to use BCMath extension instead of PHP’s built-in data types.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.