Floating point "g" format not stripping trailing zeros

Ian Kelly ian.g.kelly at gmail.com
Wed Feb 11 17:28:33 EST 2015


On Wed, Feb 11, 2015 at 3:19 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Wed, Feb 11, 2015 at 2:48 PM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>> On 11/02/2015 20:02, Hrvoje Nikšić wrote:
>>>
>>> According to the documentation of the "g" floating-point format,
>>> trailing zeros should be stripped from the resulting string:
>>>
>>> """
>>> General format. For a given precision p >= 1, this rounds the number
>>> to p significant digits and then formats the result in either
>>> fixed-point format or in scientific notation, depending on its
>>> magnitude.[...]
>>> In both cases insignificant trailing zeros are removed from the
>>> significand, and the decimal point is also removed if there are no
>>> remaining digits following it.
>>> """
>>>
>>> However, in some cases, the trailing zeros apparently remain:
>>>
>>>>>> from decimal import Decimal as D
>>>>>> x = D(1)/D(999)
>>>>>> '{:.15g}'.format(x)
>>>
>>> '0.00100100100100100'
>>>
>>> For floats, the trailing zeros are removed:
>>>
>>>>>> '{:.15g}'.format(1. / 999)
>>>
>>> '0.001001001001001'
>>>
>>> This behavior is present in both 2.7.8 and 3.4.1. Is this a bug in the
>>> formatting of Decimals?
>>>
>>
>> I'd say it's a bug.  P is 15, you've got 17 digits after the decimal place
>> and two of those are insignificant trailing zeros.
>
> Actually it's the float version that doesn't match the documentation.
> In the decimal version, sure there are 17 digits after the decimal
> place there, but the first two -- which are leading zeroes -- would
> not normally be considered significant. The float version OTOH is only
> giving you 13 significant digits when 15 were requested.
>
> For illustration, compare the same formatting with the scale ramped up
> to make it switch to exponential notation:
>
>>>> '{:.15g}'.format(D(1) / D(999000000))
> '1.00100100100100e-9'
>>>> '{:.15g}'.format(1./999000000)
> '1.001001001001e-09'

Although here's something else that is definitely an issue with the
decimal formatting:

>>> '{:.15g}'.format(D(1)/D(999000))
'0.00000100100100100100'

This has an exponent of -6, so according to the docs it should be
formatted in exponential notation.



More information about the Python-list mailing list