php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70598 Comparison fails for array values of type float
Submitted: 2015-09-28 11:27 UTC Modified: 2015-09-29 17:46 UTC
From: mv dot pestov at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.6.13 OS: Debian Wheezy
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: mv dot pestov at gmail dot com
New email:
PHP Version: OS:

 

 [2015-09-28 11:27 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-09-28 20:19 UTC] rasmus@php.net
-Status: Open +Status: Not a bug
 [2015-09-28 20:19 UTC] 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-29 17:46 UTC] mv dot pestov at gmail dot com
Thank you very much for your detailed explanation. I'll read the link you have provided by this subject.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Tue Oct 06 20:00:02 2026 UTC