Curious Omission In New-Style Formats

Chris Angelico rosuav at gmail.com
Wed Jul 13 09:00:15 EDT 2016


On Wed, Jul 13, 2016 at 9:46 PM, Dennis Lee Bieber
<wlfraed at ix.netcom.com> wrote:
> On Wed, 13 Jul 2016 00:21:17 -0600, Ian Kelly <ian.g.kelly at gmail.com>
> declaimed the following:
>
>>What if I've been doing my math with fixed-point integers (because I
>>don't know about or just don't like decimals), and now I want to
>>format them for output? Is this just wrong?
>>
>>    '{:.2f}'.format(int_value / 100)
>>
>
>         Ugh... After using integers to keep accuracy in the LSB, you know toss
> it out the window by converting to a float which may have an inexact
> representation.
>
>         Presuming you kept track of the decimal place during all those integer
> operations, format as an integer, then split it at the decimal and insert a
> "." at the spot.

Or just use divmod:

>>> "%d.%02d" % divmod(1<<200, 100)
'16069380442589902755419620923411626025222029937827928353013.76'

ChrisA



More information about the Python-list mailing list