php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42463 implicit sprintf round uses banker's algorithm.
Submitted: 2007-08-28 17:17 UTC Modified: 2007-08-28 21:36 UTC
From: dan dot ostrowski at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.2.3 OS: Linux
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: dan dot ostrowski at gmail dot com
New email:
PHP Version: OS:

 

 [2007-08-28 17:17 UTC] dan dot ostrowski at gmail dot com
Description:
------------
When rounding (implicitly) with sprintf, halfway values are rounded using a "banker's" algorithm instead of performing the way a call to round() would.

This seems inconsistent and counterintuitive for no particular reason.

Thanks!

Reproduce code:
---------------
print sprintf("%2.2f", 0.015)."<br/>";
print sprintf("%2.2f", 0.025)."<br/>";
print sprintf("%2.2f", 0.035)."<br/>";
print sprintf("%2.2f", 0.045)."<br/>";
print "<br/>";
print round(0.015, 2)."<br/>";
print round(0.025, 2)."<br/>";
print round(0.035, 2)."<br/>";
print round(0.045, 2)."<br/>";

Expected result:
----------------
0.02
0.03
0.04
0.05

0.02
0.03
0.04
0.05

Actual result:
--------------
0.01
0.03
0.04
0.04

0.02
0.03
0.04
0.05

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-08-28 21:36 UTC] jani@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://docs.sun.com/source/806-3568/ncg_goldberg.html
 
Thank you for your interest in PHP.


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sun Nov 30 13:00:01 2025 UTC