Bug #70598 [Nab]: Comparison fails for array values of type float
| From: | mv dot pestov at gmail dot com | Date: | Tue, 29 Sep 2015 17:46:10 +0000 |
| Subject: | Bug #70598 [Nab]: Comparison fails for array values of type float | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-196302@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=70598&edit=1
ID: 70598
User updated by: mv dot pestov at gmail dot com
Reported by: mv dot pestov at gmail dot com
Summary: Comparison fails for array values of type float
Status: Not a bug
Type: Bug
Package: Arrays related
Operating System: Debian Wheezy
PHP Version: 5.6.13
Block user comment: N
Private report: N
New Comment:
Thank you very much for your detailed explanation. I'll read the link you have provided by this
subject.
Previous Comments:
------------------------------------------------------------------------
[2015-09-28 20:19:06] rasmus@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.
$i += 0.2 is not going to be precise. Floating point doesn't work that way.
------------------------------------------------------------------------
[2015-09-28 11:27:11] mv dot pestov at gmail dot com
Description:
------------
When populating an array with values of type float from loop and then the comparison (==) fails. If
create an array using array() this bug not reproduces.
Test script:
---------------
<?php
$array = array();
for($i = 1.4; $i <= 2; $i += 0.2)
{
$array[] = $i;
}
if($array[3] == 2)
echo 'true';
else
echo 'false';
Expected result:
----------------
true
Actual result:
--------------
false
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=70598&edit=1