Feature or enhancement
Support fraction.Fraction both in printf-style formatting and new-style formatting. Currently, the former converts to float
and the latter is unsupported. The following example has been run on a platform with rounding behaviour “to nearest, ties to even”:
>>> from fractions import Fraction
>>> f = Fraction(2635, 1000)
>>> '%.2f' %f
'2.63'
>>> '{:.2f}'.format(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to Fraction.__format__
Python rounds down here because 2635/1000 as float
is 2.6349999999999997868371792719699442386627197265625. The output should not depend on floating point representations.
Pitch
Currently, it is difficult to obtain rounded decimal output from fractions of the fractions
module. The best way without writing my own rounding function I could find is to use Decimal(f.numerator) / Decimal(f.denominator)
after assigning the desired precision to getcontext().prec
. If output contains numbers with different precisions, one must prepare parts of the output in variables and assemble the output as one must change getcontext().prec
in between. This is awkward.