Answer the question
In order to leave comments, you need to log in
floatval() in PHP?
I apologize in advance for the stupid question, but please explain why this thing happens:
<?php
// Set the value of the variables at once.
// Originally they are read from a file, so they are represented as strings.
$a = '895.8858';
$b = '161.2595';
$sum = '1057.1453';
// Convert to fractional values using floatval();
$a = floatval($a);
$b = floatval($b);
$sum = floatval($sum);
// Add $a and $b and compare with the previously known sum. If not equal, output TRUE.
if ($sum != ($a + $b)) echo 'TRUE';
?>
Answer the question
In order to leave comments, you need to log in
In general, in theory, echo $a + $b will answer the question, but to be more specific:
0.1 + 0.7 === 0.8 // false
why?
the answer is not obvious but: 0.1 + 0.7 = 0.7999999999999999
Your arithmetic is from the same power - floating precision numbers are not exact, round up to a couple of decimal places after the comma using number_format then everything will work correctly
Because IEEE 754
Obviously, when storing numbers in the binary system, it is absolutely possible to store only those fractional numbers that consist of powers of two. The rest of the numbers are stored up to machine epsilon .
if ($sum != (float)($a + $b)) - you need to cast to a floating point number for comparison.
Question: why is the sum of $a + $b not equal to $sum, i.e. the script will output TRUE
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question