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
Leave a Reply