php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #984 round() works bad
Submitted: 1998-12-10 06:06 UTC Modified: 1998-12-10 09:01 UTC
From: segi at active dot ch Assigned:
Status: Closed Package: Misbehaving function
PHP Version: 3.0.5 OS: Linux 2.0.33
Private report: No CVE-ID: None
 [1998-12-10 06:06 UTC] segi at active dot ch
echo round( 0.5 );    // is 0 but should be 1
echo round( 1.5 );    // is 2 - ok
echo round( 2.5 );    // is 2 but sould be 3
echo round( 3.5 );    // is 4 - ok
... and so on

I fixed that by simply add 0.0001 to the values
(which are variables in my case),
but that seems not a good solution to me.

Thank you for your answers.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [1998-12-10 09:01 UTC] zeev
This has to do with the fact that floating point numbers
have limited accuracy.

0.5 is never represented as 0.5000000... with zeros all the way
to infinity, but usually as something like
0.49999999999999999998

1.5 may be represented as 1.50000000000002, etc.

Simply, you cannot rely on 0.5 being accurate, and thus
the behavir of round() can be considered undefined.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Apr 29 17:01:29 2024 UTC