0 like 0 dislike
16 views
I apologize in advance for the stupid question, but please explain why there is such a thing:

<?php<br/>

// Set the value of variables at once.
// In the original, they are read from a file, so they are represented by lines.
\$a = '895.8858';
\$b = '161.2595';
\$sum = '1057.1453';

// Converted to decimal values using floatval();
\$a = floatval(\$a);
\$b = floatval(\$b);
\$sum = floatval(\$sum);

// We add \$a and \$b and compare with the previously known amount. If not equal, output TRUE.
if (\$sum != (\$a + \$b)) echo 'TRUE';

?>

Question: why is the amount \$a + \$b is not equal to \$sum, i.e. the script will output TRUE;
| 16 views

0 like 0 dislike
Generally, in theory, echo \$a + \$b will give the answer to the question, or to be more specific then:
0.1 + 0.7 === 0.8 // false
why?
the answer is not obvious but: 0.1 + 0.7 = 0.7999999999999999
Your arithmetic of equally — floating exact not exact, round to a couple of digits after the jam with the aid number_format then everything will work correctly
by
0 like 0 dislike
Because IEEE 754
It is obvious that the storage of numbers in binary, can be absolutely sure to store only those fractions which consist of powers of two. The remaining numbers are stored with a precision machine Epsilon.
by
0 like 0 dislike
if (\$sum != (float)(\$a + \$b)) — need to bring it to floating point for comparison.
by
0 like 0 dislike
Question: why is the amount \$a + \$b is not equal to \$sum, i.e. the script will output TRUE

I guess I do not understand the question, otherwise the answer is obvious :)
by
0 like 0 dislike
Because you have variables of type float. Try in PHP to find the difference between the \$and the sum \$a + \$b. As an option — compare them as strings.
by