Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 8 additions & 23 deletions docs/numbers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -102,33 +102,19 @@ current context before formatting a number or currency:

.. code-block:: pycon

>>> from babel.numbers import decimal, format_decimal
>>> with decimal.localcontext(decimal.Context(rounding=decimal.ROUND_DOWN)):
>>> txt = format_decimal(123.99, format='#', locale='en_US')
>>> txt
>>> from decimal import ROUND_DOWN, localcontext
>>> from babel.numbers import format_decimal
>>> with localcontext() as ctx:
... ctx.rounding = ROUND_DOWN
... format_decimal(123.99, format='#', locale='en_US')
'123'

It is also possible to use ``decimal.setcontext`` or directly modifying the
instance returned by ``decimal.getcontext``. However, using a context manager
is always more convenient due to the automatic restoration and the ability to
nest them.

Whatever mechanism is chosen, always make use of the ``decimal`` module imported
from ``babel.numbers``. For efficiency reasons, Babel uses the fastest decimal
implementation available, such as `cdecimal`_. These various implementation
offer an identical API, but their types and instances do **not** interoperate
with each other.

For example, the previous example can be slightly modified to generate
unexpected results on Python 2.7, with the `cdecimal`_ module installed:
Leaving the ``with`` block restores the previous context. With the default
rounding mode, the same number rounds to the next integer:

.. code-block:: pycon

>>> from decimal import localcontext, Context, ROUND_DOWN
>>> from babel.numbers import format_decimal
>>> with localcontext(Context(rounding=ROUND_DOWN)):
>>> txt = format_decimal(123.99, format='#', locale='en_US')
>>> txt
>>> format_decimal(123.99, format='#', locale='en_US')
'124'

Changing other parameters such as the precision may also alter the results of
Expand All @@ -138,7 +124,6 @@ behaves as desired.
.. _Decimal: https://docs.python.org/3/library/decimal.html#decimal-objects
.. _Context: https://docs.python.org/3/library/decimal.html#context-objects
.. _`UTS #35 section 3.3`: https://www.unicode.org/reports/tr35/tr35-numbers.html#Formatting
.. _cdecimal: https://pypi.org/project/cdecimal/


Parsing Numbers
Expand Down