Question

PHP is erroring out on me when working with small decimals / floats. Take the following code:

$spotPrices['entry'] = 1.6591;
$price['o'] = 1.65908;

$currentresult = $spotPrices['entry'] - $price['o'];

echo $currentresult;

I would expect this to output 0.00002 (the answer). But instead it outputs: -1.99999999999E-5

Why is it doing this and, more importantly, how can I get the correct result?


I've done some searching on the forums and seen that floating points give PHP fits but haven't seen a solution or workaround that seems to answer my question.

Was it helpful?

Solution

My calculator is saying that the result should be 0.00002

use number_format:

$currentresult = number_format($spotPrices['entry'] - $price['o'], 8);

OTHER TIPS

Instead of 0.00002 you get 1.9999999999909E-5 which is 0.000019999999999909. This is due to floating point precision. Precision is platform-dependent. You can read up on it here: http://www.php.net/manual/en/language.types.float.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top