Floating point "g" format not stripping trailing zeros

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Feb 11 16:48:12 EST 2015


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.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list