Forum Moderators: coopster
It's been working fine for months now but a recent result has thrown up a bug and I just can't understand what the problem is. The overall profit was £100 in the red (-£100) on 18th March and then a win of £100 on 19th March should show a new overall profit of £0.00. However the figure -5.6843418860808E-14 is shown instead!
Here is the relevant PHP code used (which operates in a loop):
...
if($row["result"]=='Won')
{
$profit = 100;
}
if($row["result"]=='Lost')
{
$profit = ($row["odds"]-1)*(-100);
}
if($row["result"]=='N/R') // Non-Runner (neither a win nor a loss)
{
$profit = '-';
}
if($row["result"]=='Won')
{
$overall_profit = $overall_profit + $profit;
}
if($row["result"]=='Lost')
{
$overall_profit = $overall_profit + $profit;
}
echo "<tr>
<td>$date</td>
<td>$selection</td>
<td>$row[odds]</td>
<td>$row[result]</td>
<td>$profit</td>
<td>$overall_profit</td>
</tr>";
...
Altering the previous results so that the overall profit does not hit exactly £0.00 eliminates the funny long number, so I guess it must be something in the maths to do with ending up with £0.00
Anyone got any ideas?
Inbound's solution results in the following error: "Fatal error: Call to undefined function: int()"
I tried the following but it did not work, either:
if($row["result"]=='Won')
{
$overall_profit = int $overall_profit + $profit;
}
I have also searched for "PHP precision method" but come up blank.
Any other ideas?
** EDIT **
I have also searched the PHP documentation but can't find anyone experiencing similar problems
You could also try the number_format() function
[gr2.php.net...]
So why does PHP behave unexpectedly when adding and subtracting what I thought were simple whole numbers? I guess it will be something to do with the fact that unless I specify the variable as a number using number_format(), PHP treats it like a string or something like that?
The int() syntax is used in excell rather than PHP, different syntax required in PHP.
The strange result is due to floating point numbers being used when not appropriate. The returned number that looked so strange is in fact a tiny anomoly but it looks very strange when printed with no formatting. The lesson from this is to anticipate such strange results and code accordingly, either using the correct variable type or using formatting.
Although I have been coding PHP for a few years and have used number_format() before when it was obvious that the decimal places would need to be specified, I never knew that seemingly whole numbers would need to be specially formatted. Oh well, you code and learn! ;) Thanks again.