Home » Support » Help Articles » Precision of Floating Point Numbers in PHP

Precision of Floating Point Numbers in PHP

Back to Help Articles Home


The floating point numbers can be specified by any of the following syntaxes as shown below.

<?php
$iNum1 = 2.143;
$iNum2 = 2.1e4;
$iNum3 = 2E-10;
?>

Depending on the platform on which PHP is running the size of float differs. The 64 bit IEEE format has a precision roughly up to 14 decimal places. The implicit precision of a normal IEEE 754 double precision number is slightly less than 16 digits, which will give a maximum relative error due to rounding in the order of 1.11e-16. So the floating point numbers have very limited precision. Also, we can represent the rational numbers as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results as shown below.

Example 1:

<?php
$iNum1 = '0.1';
$iNum2 = '0.5';
$sResult = floor(($iNum1 + $iNum2)*10);
print $sResult; //Output 5
?>

If normal arithmetic is taken into account then the output shall be 6. However PHP usually returns 5 because the internal representation is something like 5.9999999999999991118….

Let us take another example where we shall compare to floating point numbers as shown below.

Example 2:

<?php
$iVal1 = 9.00 + 2.44 + 1.28 + 3.88; // 16.60
$iVal2 = 16.60;

if ($iVal1 == $iVal2)
{
print 'Floating point numbers are equal';
}
else
{
print 'Floating point numbers are not equal';
}
?>

When the above code is run in PHP it prints "Floating point are not equal". Even though normal arithmetic says both values should be equal, PHP doesn't think they are. This is because internally, computers use a binary floating-point format that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all. When the code is compiled or interpreted, floating point numbers like "0.1" is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.



Updated on Nov 11, 2015

The techReview is an online magazine by Batoi and publishes articles on current trends in technologies across different industry verticals and areas of research. The objective of the online magazine to provide an insight into cutting-edge technologies in their evolution from labs to market.

Visit techReview


English - IN (USD)
New Users? Signup.     Existing Users? Login.