Representing numbers by using the decimal module

To create a decimal number, type the following, substituting your number or object inside the parentheses:

Decimal(numerical object)

The numericai_object can be any of these types of data:

An integer

Decimal(3) A calculation

Decimal(3*5)

A number represented as a string

Decimal("3.2")

A float converted to a string with the str() function >>> x = 3.2 >>> Decimal(str(x)) Decimal("3.2")

Warning You can't use floating point numbers directly with the decimal module. They must be converted to strings first.

Tip To create a decimal from a three-item tuple, use this format for the tuple:

1. The first item in the tuple is 0 (for positive) or 1 (for negative).

2. The second item is another (nested) tuple containing the digits of the number, one element for each digit.

3. The third item is a positive or negative integer specifying the exponent.

Decimal numbers work with Python's regular math functions. Give them names and use the names as arguments, or insert them directly as arguments:

Decimal("81")

Was this article helpful?

0 0

Post a comment