@@ -101,6 +101,10 @@ another rational number, or from a string.
101
101
.. versionchanged :: 3.12
102
102
Space is allowed around the slash for string inputs: ``Fraction('2 / 3') ``.
103
103
104
+ .. versionchanged :: 3.12
105
+ :class: `Fraction ` instances now support float-style formatting, with
106
+ presentation types `"e" `, `"E" `, `"f" `, `"F" `, `"g" `, `"G" ` and `"%"" `.
107
+
104
108
.. attribute :: numerator
105
109
106
110
Numerator of the Fraction in lowest term.
@@ -187,6 +191,31 @@ another rational number, or from a string.
187
191
``ndigits `` is negative), again rounding half toward even. This
188
192
method can also be accessed through the :func: `round ` function.
189
193
194
+ .. method :: __format__(format_spec, /)
195
+
196
+ This method provides support for float-style formatting of
197
+ :class: `Fraction ` instances via the :meth: `str.format ` method, the
198
+ :func: `format ` built-in function, or :ref: `Formatted string literals
199
+ <f-strings>`. The presentation types `"e" `, `"E" `, `"f" `, `"F" `, `"g" `,
200
+ `"G"`` and `"%" ` are supported. For these presentation types, formatting
201
+ for a :class: `Fraction ` object `x ` behaves as though the object `x ` were
202
+ first converted to :class: `float ` and then formatted using the float
203
+ formatting rules, but avoids the loss of precision that might arise as
204
+ a result of that conversion.
205
+
206
+ Here are some examples::
207
+
208
+ >>> from fractions import Fraction
209
+ >>> format (Fraction(1 , 7 ), ' .40g' )
210
+ '0.1428571428571428571428571428571428571429'
211
+ >>> format (Fraction(' 1234567.855' ), ' _.2f' )
212
+ '1_234_567.86'
213
+ >>> f " { Fraction(355 , 113 ):* > 20. 6e } "
214
+ '********3.141593e+00'
215
+ >>> old_price, new_price = 499 , 672
216
+ >>> " {:.2% } price increase" .format(Fraction(new_price, old_price) - 1 )
217
+ '34.67% price increase'
218
+
190
219
191
220
.. seealso ::
192
221
0 commit comments