Skip to content

Commit ad6396e

Browse files
miss-islingtonskirpichevrruuaanngStanFromIrelandhugovk
authored
[3.14] decimal docs: specification link and examples (GH-128698) (#142804)
decimal docs: specification link and examples (GH-128698) (cherry picked from commit 2450be6) Co-authored-by: Sergey B Kirpichev <skirpichev@gmail.com> Co-authored-by: RUANG (James Roy) <longjinyii@outlook.com> Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
1 parent 8a2ea91 commit ad6396e

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

Doc/library/decimal.rst

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,12 @@ The :mod:`decimal` module provides support for fast correctly rounded
3434
decimal floating-point arithmetic. It offers several advantages over the
3535
:class:`float` datatype:
3636

37-
* Decimal "is based on a floating-point model which was designed with people
38-
in mind, and necessarily has a paramount guiding principle -- computers must
39-
provide an arithmetic that works in the same way as the arithmetic that
40-
people learn at school." -- excerpt from the decimal arithmetic specification.
37+
* Decimal "is based on a `floating-point model
38+
<https://speleotrove.com/decimal/damodel.html#refnumber>`__ which was designed
39+
with people in mind, and necessarily has a paramount guiding principle --
40+
computers must provide an arithmetic that works in the same way as the
41+
arithmetic that people learn at school." -- excerpt from the decimal
42+
arithmetic specification.
4143

4244
* Decimal numbers can be represented exactly. In contrast, numbers like
4345
``1.1`` and ``2.2`` do not have exact representations in binary
@@ -238,6 +240,26 @@ floating-point flying circus:
238240
>>> c % a
239241
Decimal('0.77')
240242

243+
Decimals can be formatted (with :func:`format` built-in or :ref:`f-strings`) in
244+
fixed-point or scientific notation, using the same formatting syntax (see
245+
:ref:`formatspec`) as builtin :class:`float` type:
246+
247+
.. doctest::
248+
249+
>>> format(Decimal('2.675'), "f")
250+
'2.675'
251+
>>> format(Decimal('2.675'), ".2f")
252+
'2.68'
253+
>>> f"{Decimal('2.675'):.2f}"
254+
'2.68'
255+
>>> format(Decimal('2.675'), ".2e")
256+
'2.68e+0'
257+
>>> with localcontext() as ctx:
258+
... ctx.rounding = ROUND_DOWN
259+
... print(format(Decimal('2.675'), ".2f"))
260+
...
261+
2.67
262+
241263
And some mathematical functions are also available to Decimal:
242264

243265
>>> getcontext().prec = 28

0 commit comments

Comments
 (0)