This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Incorrect string formatting of float values in Python 2.7
Type: Stage: resolved
Components: Library (Lib) Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: eric.smith, pushpendre rastogi
Priority: normal Keywords:

Created on 2015-03-10 14:26 by pushpendre rastogi, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg237769 - (view) Author: pushpendre rastogi (pushpendre rastogi) Date: 2015-03-10 14:26
Hi, The string formatting module in python 2.7 incorrectly formats floating point values. The following code shows the problem

>>> print "%.10s"%(-7.7176718e-05)
-7.7176718
>> print "%.10s"%(-0.0000771767)
-7.71767e-

Ideally the code should have thrown an exception (first preference)
or it should have printed  -0.0000771767 (second preference) or -7.7176718e-05 (third preference)
msg237772 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2015-03-10 15:01
By using %s, you're asking the formatting code to first convert the parameter to a string. Then, by using .10, you're asking it to truncate the value.

It's essentially equivalent to:

>>> str(-7.7176718e-05)
'-7.7176718e-05'
>>> str(-7.7176718e-05)[:10]
'-7.7176718'

and:

>>> str(-0.0000771767)
'-7.71767e-05'
>>> str(-0.0000771767)[:10]
'-7.71767e-'

This isn't a bug. If you want more control over the formatting, use %f, %e, or %g:

>>> '%.10f' % -7.7176718e-05
'-0.0000771767'
History
Date User Action Args
2022-04-11 14:58:13adminsetgithub: 67815
2015-03-10 15:01:09eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg237772

resolution: not a bug
stage: resolved
2015-03-10 14:26:26pushpendre rastogicreate