Solving Floating point number precision lost problem in PHP


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.

var_dump($no_of_time); //displays float(5)
   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.

var_dump($no_of_time); //display string(1) "5"
   echo $i;

Now the above, loop runs 5 times without any problem.

Popularity: 2% [?]

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Related Posts

» Getting random number between range of two numbers in JavaScript
» Top Floating message box using jQuery
» Letter to Bill Gates about the flaw in Microsoft’s Products
» Php function to validate two decimal places of a number

Write a Comment


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by, Custom Theme and Calling Card Company.