[Python-ideas] %-formatting with Decimals

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 11 13:44:00 CET 2014


During recent discussions I came across something unfortunate with
formatting Decimals.

Formatting with .format works as I would want:

>>> from decimal import Decimal as D
>>> '{:1.0e}'.format(D('1.123e+1000'))
'1e+1000'
>>> '{:1.0e}'.format(D('1.123e-1000'))
'1e-1000'
>>> '{:.50f}'.format(D('1.1'))
'1.10000000000000000000000000000000000000000000000000'

But %-formatting coerces to float:

>>> '%1.0e' % D('1.123e-1000')
'0e+00'
>>> '%1.0e' % D('1.123e+1000')
'inf'
>>> '%.50f' % D('1.1')
'1.10000000000000008881784197001252323389053344726562'

Am I doing this wrong? Is this just a limitation of the old-style %
formatting or something that could possibly be improved?


Oscar


More information about the Python-ideas mailing list