N
N
Nikolai Alexandrov2011-01-28 18:48:56
PHP
Nikolai Alexandrov, 2011-01-28 18:48:56

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';
 
?>

Question: why is the sum of $a + $b not equal to $sum, i.e. the script will output TRUE;

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Anatoly, 2011-01-28
@dos

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

T
TimTowdy, 2011-01-28
@TimTowdy

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 .

D
Dunadan, 2011-01-28
@Dunadan

if ($sum != (float)($a + $b)) - you need to cast to a floating point number for comparison.

A
agul, 2011-01-28
@agul

Question: why is the sum of $a + $b not equal to $sum, i.e. the script will output TRUE

I guess I didn't understand the question, otherwise the answer is obvious :)

H
hayk, 2011-01-28
@hayk

Because your variable type is float. Try to find the difference between $sum and $a + $b in PHP. Alternatively, compare them as strings.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question