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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Fri May 17 23:01:32 2024 UTC