Bug #67201 [Opn->Nab]: Simple comparison of two floats gives incorrect result

From: Date: Sun, 04 May 2014 08:19:43 +0000
Subject: Bug #67201 [Opn->Nab]: Simple comparison of two floats gives incorrect result
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-185619@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=67201&edit=1 ID: 67201 Updated by: requinix@php.net Reported by: ashley at ashleydawson dot co dot uk Summary: Simple comparison of two floats gives incorrect result -Status: Open +Status: Not a bug Type: Bug Package: *General Issues Operating System: Ubuntu 13.10 PHP Version: 5.5.12 Block user comment: N Private report: N New Comment: 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 Previous Comments: ------------------------------------------------------------------------ [2014-05-04 07:42:32] 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'; ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=67201&edit=1

« previous php.bugs (#185619) next »