Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very simple PHP addition problem

Tags:

php

I think I have been looking at this for too long. Why is this code printing 'no', it should be printing 'yes' shouldn't it? I've tried it on PHP 5.3 and PHP 5.2 and both print 'no'.

<?php

$total = 14.05;
$var1 = 0;
$var2 = 0.11;
$var3 = 13.94;

if(($var1 + $var2 + $var3) == $total)
{
    echo 'yes';
}
else
{
    echo 'no';
}

?>
like image 223
RandomCoder Avatar asked Dec 16 '22 15:12

RandomCoder


1 Answers

See Comparing floating point numbers.

This doesn't work because floating point numbers are not represented exactly. A small rounding error is enough for the equality operator to fail.

like image 122
MaxVT Avatar answered Jan 07 '23 05:01

MaxVT