php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #68972 Mystery in $n - floor($n)
Submitted: 2015-02-02 13:33 UTC Modified: 2015-03-19 21:24 UTC
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:0 of 1 (0.0%)
From: genesismemori at yandex dot com Assigned: cmb (profile)
Status: Closed Package: Systems problem
PHP Version: 5.6.5 OS: CentOS 6.5 (Final)
Private report: No CVE-ID: None
 [2015-02-02 13:33 UTC] genesismemori at yandex dot com
Description:
------------
$n - floor($n) always returns the expected result, but when comparing it to the same (float) value it evaluates to FALSE. This is regardless of whether the value comparing it to is of the same type or not. A workaround to this problem is converting the number to a string first, and then back to float.

Test script:
---------------
function expr_dump( $val, $equals ) {
	print $val." == ".$equals." ";
	var_dump( $val == $equals );
}

function test( $v, $w ) {
	$n = $v - floor($v);
	expr_dump( $n, $w );
	$n = strval( $n );
	$n = floatval( $n );
	expr_dump( $n, $w );
}

test(2.95, .95);

Expected result:
----------------
test(0.95, .95): true, true
test(1.95, .95): true, true
test(2.95, .95): true, true
test(30.95, .95): true, true

Actual result:
--------------
test(0.95, .95): true, true
test(1.95, .95): true, true
test(2.95, .95): false, true // BAD!
test(30.95, .95): false, true // BAD!

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-02-02 15:39 UTC] cmbecker69 at gmx dot de
This is not a bug in PHP. See the manual page on "Floating point
numbers"[1], especially the warning regarding "Floating point
precision".

[1] <http://php.net/manual/en/language.types.float.php>
 [2015-03-19 21:24 UTC] cmb@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: cmb
 [2015-03-19 21:24 UTC] cmb@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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Dec 30 14:01:28 2024 UTC