[ python-Bugs-1479776 ] float->str rounding bug

SourceForge.net noreply at sourceforge.net
Mon May 1 17:54:47 CEST 2006


Bugs item #1479776, was opened at 2006-05-01 10:37
Message generated for change (Comment added) made by tim_one
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1479776&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
>Group: Not a Bug
>Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Michael Nolta (mrnolta)
Assigned to: Nobody/Anonymous (nobody)
Summary: float->str rounding bug

Initial Comment:
Hi,

Here's my problem:

  >>> print "%.2f" % 2.195
  2.19

The output should be "2.20".

It's sensitive to whether the value is greater than 1.
For example, this works:

  >>> print "%.4f" % 2.195e-2
  0.0220

Here's my full version info:

  Python 2.4.1 (#1, May 16 2005, 15:19:29)
  [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2

-Mike

----------------------------------------------------------------------

>Comment By: Tim Peters (tim_one)
Date: 2006-05-01 11:54

Message:
Logged In: YES 
user_id=31435

This isn't a bug.  You should read the Python Tutorial's
Appendix on floating-point issues.  As you can see from

>>> 2.195
2.1949999999999998

the closest representable float is actually a little bit
smaller than the decimal 2.195, so there's no reason for it
to "round up".  Try the same thing in C (or any other
language exposing your hardware's binary floating point),
and you should see the same result.

If you need exact decimal values, use Python's "decimal"
module instead.

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1479776&group_id=5470


More information about the Python-bugs-list mailing list