Floating point "g" format not stripping trailing zeros

Grant Edwards invalid at invalid.invalid
Fri Feb 13 16:22:40 EST 2015


On 2015-02-13, Dave Angel <davea at davea.name> wrote:
> On 02/13/2015 03:33 PM, Grant Edwards wrote:
>> On 2015-02-13, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>>
>>> Significant digits are within the precision of the calculation.
>>> Writing 1.230 indicates that the fourth digit is known to be zero.
>>> Writing 1.23 outside a context of exact calculation indicates that the
>>> fourth digit is unknown due to insufficient precision.
>>
>> I knew that, but I was asking in the context of float/decimal's
>> formatting function.  I didn't realize that float and/or decimal had a
>> "significant digit" property, and therefore possess significant vs.
>> insignificant trailing zeros when represented in base-10.
>
> Just jumping in here, and somebody please correct me if I mess it up.
>
> Built-in binary floating point (float) has a fixed number of bits for 
> mantissa, and separate bits for exponent and sign.  Because of those 
> fixed number of bits, no assumption can be made as to how many of them 
> are relevant.

Right.

> On the other hand, the Decimal package has a way that the programmer
> can tell how many digits to use at each stage of the calculation.

That's what surpised me.  From TFM:

https://docs.python.org/2/library/decimal.html:

 * The decimal module incorporates a notion of significant places so that
   1.30 + 1.20 is 2.50. The trailing zero is kept to indicate
   significance. This is the customary presentation for monetary
   applications. For multiplication, the “schoolbook” approach uses
   all the figures in the multiplicands. For instance, 1.3 * 1.2 gives
   1.56 while 1.30 * 1.20 gives 1.5600.

> So if the programmer bothered to set it to the correct precision, the
> print logic (could) use that to decide about trailing zeroes.  I have
> no idea whether it does, but this thread would seem to say it does.

It seems to. Pretty cool.

-- 
Grant Edwards               grant.b.edwards        Yow! LOOK!!  Sullen
                                  at               American teens wearing
                              gmail.com            MADRAS shorts and "Flock of
                                                   Seagulls" HAIRCUTS!



More information about the Python-list mailing list