Curious Omission In New-Style Formats
Jussi Piitulainen
jussi.piitulainen at helsinki.fi
Wed Jul 13 09:16:02 EDT 2016
Chris Angelico writes:
> 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'
I'm not quite ready to blame floating point for this difference yet:
>>> "%d.%02d" % divmod(-1,100)
'-1.99'
>>> "%.2f" % (-1/100)
'-0.01'
More information about the Python-list
mailing list