|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #69517 round() does something weird on result of pow()
Submitted: 2015-04-23 18:45 UTC Modified: 2015-04-23 22:20 UTC
From: leafface at gmail dot com Assigned: cmb (profile)
Status: Not a bug Package: Math related
PHP Version: 5.5.24 OS: Mac OS X
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 this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Bug Type:
From: leafface at gmail dot com
New email:
PHP Version: OS:


 [2015-04-23 18:45 UTC] leafface at gmail dot com
round() acts weird in some cases when pow() theoretically returns a round number. The bug doesn't occur if precision for round() is set and is greater than 14.

(Sorry, I actually have PHP 5.5.14, but it's pretty unlikely this has been resolved since.)

Test script:

$n = pow(8, 2/3);

	($n == round($n) ? 'true' : 'false').
	($n == round($n, 14) ? 'true' : 'false').
	($n == round($n, 15) ? 'true' : 'false');

Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2015-04-23 20:08 UTC]
-Status: Open +Status: Not a bug -Package: Unknown/Other Function +Package: Math related -Assigned To: +Assigned To: cmb
 [2015-04-23 20:08 UTC]
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:

Thank you for your interest in PHP.

Never ever compare floating point values for equality. :)
 [2015-04-23 20:34 UTC] leafface at gmail dot com
"Floating point values have a limited precision." - Actually what's really strange in my bug report is that "The bug doesn't occur if precision for round() is set and is greater than 14.", i.e. the bug doesn't only occur if there's no precision set for round(), but also if the precision is less than 15, even if it's 1! Meaning this statement for example results false:  $n == round($n, 1)
 [2015-04-23 21:34 UTC]
pow(8, 2/3) is 3.9999999999999956 … When you then do a round($n, 15) operation, it rounds to 3.999999999999996 which is the same as 3.9999999999999956 internally, thus returning true.

Everything with second parameter smaller than 15 rounds to float(4), which isn't equal to $n.
 [2015-04-23 22:20 UTC] leafface at gmail dot com
Okay I get it now.
“echo $n” says 4, that's what confused me, but also “$n<4” is true.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 17 06:01:28 2024 UTC