[issue23602] Implement __format__ for Fraction

Tuomas Suutari report at bugs.python.org
Sun Mar 29 19:07:02 CEST 2015


Tuomas Suutari added the comment:

On 29 March 2015 at 19:54, Serhiy Storchaka wrote:
> I think that Decimal is not needed for Fraction.__format__ (and I'm not sure that issue23602v4.patch is correct).

Of course it's not needed. I'm using it to avoid re-implementing all
the various formatting variations that can be controlled with the
fill/align/sign/width/,/precision/type parameters
(https://docs.python.org/3/library/string.html#formatspec). IMHO those
should be supported as they are with floats and Decimals.

> The correct way to format Fraction as fixed-precision decimal is to use Fraction.__round__() or similar algorithm. The implementation can look like:
>
>     f = self.__round__(prec)
>     i = int(f)
>     return '%d.%0*d' % (i, prec, abs(f - i) * 10**prec)

Why this would be more correct than delegating the rounding (and
formatting) to Decimal.__format__? (Then we just have to make sure
that we have enough precision in the decimal context we're operating
in. That's what I got wrong in the previous round.)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23602>
_______________________________________


More information about the Python-bugs-list mailing list