stilts77 stilts77 - 1 year ago 68
PHP Question

Incorrect calculation using decimals in php

I have some arrays, holding the numbers for a multiplication quiz. Here are some examples:


These numbers are used to calculate some answers that are placed on a button and the user has to click on the correct answer.

// the correct answer
// wrong answer no. 1
if ($w1e==$d){
// wrong answer no. 2
if ($w2e==$d){

There is a check on the receiving page of the POSTing to see if the user has indeed got the correct answer:

$d=$c * $b;

if ($subby==$d){

echo "<script></script>";}
echo "<script></script>";



if ($subby==$d) {
echo "Well done!";
echo "<h3>The button you pressed said: ".$subby;
echo "</h3><br><h2>";
echo $b."x".$c."=".$subby;
echo "</h2><br>";
echo "<h3>Your streak is worth ".$_SESSION["score"];

else {
echo "<h1>No!<br>";
echo $b."x".$c."=".$d;
echo "<br>";
echo "Your streak has been reset to 0!</h1>";

Now, when I have whole numbers: no problem. But the decimals are causing a problem. My code is telling the player that a correct calculation is wrong!

I've spent some time echoing out simple decimal multiplications and the output is correct (so no truncating of decimals or anything like that)...

Why the inaccuracy?

Answer Source

I'm guessing that you are comparing floating point numbers in the same way as integers.

It can't possibly work because of the nature of floating point numbers.

You can't check equality of floating point values, but you can ask if their absolute difference is within a tolerance that you specify. Here's pseudo code to show what I mean:

float x = 1.1;
float y = 1.2;
float tolerance = 1.0e-3;
if (abs(x-y) <= tolerance) {  // abs() is an absolute value function
   print "within tolerance"
} else {
   print "not within tolerance"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download