Skip to content

Commit e579a8c

Browse files
OTheDevestyxx
authored andcommitted
pythongh-101575: document Decimal.__round__() (pythonGH-101737)
1 parent 4b5ad7e commit e579a8c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Doc/library/decimal.rst

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -897,6 +897,48 @@ Decimal objects
897897
:const:`Rounded`. If given, applies *rounding*; otherwise, uses the
898898
rounding method in either the supplied *context* or the current context.
899899

900+
Decimal numbers can be rounded using the :func:`.round` function:
901+
902+
.. describe:: round(number)
903+
.. describe:: round(number, ndigits)
904+
905+
If *ndigits* is not given or ``None``,
906+
returns the nearest :class:`int` to *number*,
907+
rounding ties to even, and ignoring the rounding mode of the
908+
:class:`Decimal` context. Raises :exc:`OverflowError` if *number* is an
909+
infinity or :exc:`ValueError` if it is a (quiet or signaling) NaN.
910+
911+
If *ndigits* is an :class:`int`, the context's rounding mode is respected
912+
and a :class:`Decimal` representing *number* rounded to the nearest
913+
multiple of ``Decimal('1E-ndigits')`` is returned; in this case,
914+
``round(number, ndigits)`` is equivalent to
915+
``self.quantize(Decimal('1E-ndigits'))``. Returns ``Decimal('NaN')`` if
916+
*number* is a quiet NaN. Raises :class:`InvalidOperation` if *number*
917+
is an infinity, a signaling NaN, or if the length of the coefficient after
918+
the quantize operation would be greater than the current context's
919+
precision. In other words, for the non-corner cases:
920+
921+
* if *ndigits* is positive, return *number* rounded to *ndigits* decimal
922+
places;
923+
* if *ndigits* is zero, return *number* rounded to the nearest integer;
924+
* if *ndigits* is negative, return *number* rounded to the nearest
925+
multiple of ``10**abs(ndigits)``.
926+
927+
For example::
928+
929+
>>> from decimal import Decimal, getcontext, ROUND_DOWN
930+
>>> getcontext().rounding = ROUND_DOWN
931+
>>> round(Decimal('3.75')) # context rounding ignored
932+
4
933+
>>> round(Decimal('3.5')) # round-ties-to-even
934+
4
935+
>>> round(Decimal('3.75'), 0) # uses the context rounding
936+
Decimal('3')
937+
>>> round(Decimal('3.75'), 1)
938+
Decimal('3.7')
939+
>>> round(Decimal('3.75'), -1)
940+
Decimal('0E+1')
941+
900942

901943
.. _logical_operands_label:
902944

0 commit comments

Comments
 (0)