
The problem of precision lost in floating point number in PHP haunted me for about 10 minutes yesterday but I quickly figured out the problem and solved it as I was aware of this problem. But, I would like to post here it here so that many others PHP programmers, who are not aware with this kind of problem ,get solution easily and don’t get stuck with it.
Calculation problem floating Point number in PHP
First of all, let me show you a small piece of example of the PHP code which I was working on.
$no_of_time=(0.60-0.55)*100;
var_dump($no_of_time); //displays float(5)
for($i=1;$i<=$no_of_time;$i++)
{
echo $i;
}
In the above code, the line var_dump($no_of_time); displays float(5). Ok, this is a expected result. But what about the loop, which runs just for 4 time. The above loop runs just for four time although var_dump () outputs that it is 5. Yes, it is 5 but with lost precision and that why never ever trust on the regular arithematic calculation with the floating point numbers in PHP. It always gives the wrong result because of the problem of lost precision. You can also see this warning in the PHP’s website.
Solving the problem of floating point precision in PHP
To solve this problem in floating point number, you need the function which calculates and support the calculation of floating point number of any precision. And, I recommend you to use BC Math functions, the binary calculator, of PHP for calculations of floating point number to prevent yourself from the problem of precision lost. But note down that, these functions always returns calculated output as string.Now, let’s try to solve the problem of above code rewrite it using bcsub and bcmul functions of PHP.
$no_of_time=bcmul(bcsub(0.60,0.55,2),100);
var_dump($no_of_time); //display string(1) "5"
for($i=1;$i<=$no_of_time;$i++)
{
echo $i;
}
Now the above, loop runs 5 times without any problem.
|
This page was last modified on 14 Sep 2011 at 16:38:37. |
Gautam Kumar EDP Manager |
» CodeIgniter A recommendation for PHP Programmer
» PHP Framworks Why when and which
» Solving Floating point number precision lost problem in PHP
» Handling array of HTML Form Elements in JavaScript and PHP
» How to filter user submitted data easily in PHP
» Prevent form post request from another domain in PHP
» Flaw in and or logical operator php
» Default arguments functions php
» Submit Form without Refreshing Page with Jquery
» MySQL Performance Tips
» Free ajax chat applications in PHP
» Return More Than One Value From a Function in PHP
» PHP Optimization Tips
» PHP Error Handling
» Useful PHP Classes and Libraries
» Useful Tools For PHP Developers
» PHP Frameworks
» Web based HTML Editors
» 301 redirect in PHP and .htaccess
» Hiding PHP file extension
» Rredirect Browser HTTPS SSL PHP
» Tighten php security functions
» PHP Framworks
