The decimal Module

A Python float is a binary floating-point number, normally in accordance with the standard known as IEEE 754 and implemented in hardware in modern computers. A concise, practical introduction to floating-point arithmetic and its issues can be found in David Goldberg’s essay “What Every Computer Scientist Should Know about Floating-Point Arithmetic,” at http://docs.sun.com/source/806-3568/ncg_goldberg.html. Often, particularly for money-related computations, you may prefer to use decimal floating-point numbers; Python 2.4 supplies an implementation of the standard known as IEEE 854, for base 10, in standard library module decimal. At http://docs.python.org/lib/module-decimal.html, you can find complete reference documentation, pointers to the applicable standards, a tutorial, and an advocacy for decimal. Here, I cover only a small subset of decimal’s functionality that corresponds to the most frequently used parts of the module.

Module decimal supplies a class Decimal whose immutable instances are decimal numbers, exception classes, and classes and functions to deal with the arithmetic context, which specifies such things as precision, rounding, and which computational anomalies (such as division by zero, overflow, underflow, and so on) will raise exceptions if they occur. In the default context, precision is 28 decimal digits, rounding is “half-even” (round results to the closest representable decimal number: when a result is exactly halfway between two such numbers, ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.