php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #67201 Simple comparison of two floats gives incorrect result
Submitted: 2014-05-04 07:42 UTC Modified: 2014-05-04 08:19 UTC
From: ashley at ashleydawson dot co dot uk Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.5.12 OS: Ubuntu 13.10
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: ashley at ashleydawson dot co dot uk
New email:
PHP Version: OS:

 

 [2014-05-04 07:42 UTC] ashley at ashleydawson dot co dot uk
Description:
------------
The exact PHP version is PHP 5.5.3-1ubuntu2.3 (I was unable to find this in the version list).

Here is an example of the issue:

if (((float)8568.2 + (float)-614) == (float)7954.2) {
    echo 'Match';
}
else {
    echo 'No Match';
}

The result of this comparison is always false, resulting in "No Match".

The expected result is true or "Match" as 8568.2 + -614 = 7954.2

Example run via PHP HTTP Server.

PHP Modules:

[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dba
dom
ereg
exif
fileinfo
filter
ftp
gettext
hash
iconv
intl
json
libxml
mbstring
mhash
mongo
mysql
mysqli
openssl
pcntl
pcre
PDO
pdo_mysql
Phar
posix
readline
Reflection
session
shmop
SimpleXML
soap
sockets
SPL
standard
sysvmsg
sysvsem
sysvshm
tokenizer
wddx
xml
xmlreader
xmlwriter
Zend OPcache
zip
zlib

[Zend Modules]
Zend OPcache




Test script:
---------------
if (((float)8568.2 + (float)-614) == (float)7954.2) {
    echo 'Match';
}
else {
    echo 'No Match';
}


Expected result:
----------------
echo 'Match';

Actual result:
--------------
echo 'No Match';

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-05-04 08:19 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2014-05-04 08:19 UTC] requinix@php.net
Floating point values have a limited precision. Hence a value might 
not have the same string representation after any processing. That also
includes writing a floating point value in your script and directly 
printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE
754 is, read this:
http://www.floating-point-gui.de/

Thank you for your interest in PHP.

round() your numbers before the comparison. In that example, round()ing after the addition is sufficient.

round(8568.2 + -614.0, 1) == 7954.2
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 19:00:01 2026 UTC