Skip to content

Commit 3d21af2

Browse files
committed
Add documentation
1 parent 48629b7 commit 3d21af2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Doc/library/fractions.rst

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ 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"` and `"%""`.
107+
104108
.. attribute:: numerator
105109

106110
Numerator of the Fraction in lowest term.
@@ -187,6 +191,31 @@ another rational number, or from a string.
187191
``ndigits`` is negative), again rounding half toward even. This
188192
method can also be accessed through the :func:`round` function.
189193

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+
190219

191220
.. seealso::
192221

0 commit comments

Comments
 (0)