@@ -101,6 +101,11 @@ another rational number, or from a string.
101101 .. versionchanged :: 3.12
102102 Space is allowed around the slash for string inputs: ``Fraction('2 / 3') ``.
103103
104+ .. versionchanged :: 3.12
105+ :class: `Fraction ` instances now support float-style formatting, with
106+ presentation types ``"e" ``, ``"E" ``, ``"f" ``, ``"F" ``, ``"g" ``, ``"G" ``
107+ and ``"%"" ``.
108+
104109 .. attribute :: numerator
105110
106111 Numerator of the Fraction in lowest term.
@@ -193,6 +198,29 @@ another rational number, or from a string.
193198 ``ndigits `` is negative), again rounding half toward even. This
194199 method can also be accessed through the :func: `round ` function.
195200
201+ .. method :: __format__(format_spec, /)
202+
203+ Provides support for float-style formatting of :class: `Fraction `
204+ instances via the :meth: `str.format ` method, the :func: `format ` built-in
205+ function, or :ref: `Formatted string literals <f-strings >`. The
206+ presentation types ``"e" ``, ``"E" ``, ``"f" ``, ``"F" ``, ``"g" ``, ``"G" ``
207+ and ``"%" `` are supported. For these presentation types, formatting for a
208+ :class: `Fraction ` object ``x `` follows the rules outlined for
209+ the :class: `float ` type in the :ref: `formatspec ` section.
210+
211+ Here are some examples::
212+
213+ >>> from fractions import Fraction
214+ >>> format(Fraction(1, 7), '.40g')
215+ '0.1428571428571428571428571428571428571429'
216+ >>> format(Fraction('1234567.855'), '_.2f')
217+ '1_234_567.86'
218+ >>> f"{Fraction(355, 113):*>20.6e}"
219+ '********3.141593e+00'
220+ >>> old_price, new_price = 499, 672
221+ >>> "{:.2%} price increase".format(Fraction(new_price, old_price) - 1)
222+ '34.67% price increase'
223+
196224
197225.. seealso ::
198226
0 commit comments