# Python Decimal Module

The `decimal` module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the `float` datatype, such as exact representation of decimal numbers (no binary floating-point errors) and user-definable precision.

## Importing the Module

```python
from decimal import Decimal, getcontext
```

## Creating Decimals

You can create `Decimal` instances from integers, strings, floats, or tuples.

### From Integers and Strings

Creating from integers or strings is exact.

```python
from decimal import Decimal

d1 = Decimal(10)
d2 = Decimal("10.5")

print(d1) # Output: 10
print(d2) # Output: 10.5
```

### From Floats

Creating from floats can reveal the inherent inaccuracy of binary floating-point numbers.

```python
d3 = Decimal(0.1)
print(d3)
# Output: 0.1000000000000000055511151231257827021181583404541015625
```

To get the exact decimal representation of a float as a human would write it, convert it to a string first.

```python
d4 = Decimal(str(0.1))
print(d4) # Output: 0.1
```

## Arithmetic Operations

`Decimal` objects support standard arithmetic operations.

```python
a = Decimal("0.1")
b = Decimal("0.2")
c = a + b

print(c) # Output: 0.3
# Compare with float: 0.1 + 0.2 = 0.30000000000000004
```

## Context and Precision

The `decimal` module uses a context to control precision and rounding.

### Getting and Setting Precision

You can access the current context using `getcontext()`.

```python
from decimal import getcontext

# Default precision is usually 28
print(getcontext().prec)

# Change precision
getcontext().prec = 6
print(Decimal(1) / Decimal(7)) # Output: 0.142857
```

### Rounding

You can also set the rounding mode.

```python
import decimal

getcontext().rounding = decimal.ROUND_HALF_UP
print(Decimal("2.5").quantize(Decimal("1"))) # Output: 3

getcontext().rounding = decimal.ROUND_HALF_DOWN
print(Decimal("2.5").quantize(Decimal("1"))) # Output: 2
```

## Comparison

`Decimal` objects can be compared with other `Decimal` objects and integers. Comparison with floats is also supported but can be tricky due to precision.

```python
print(Decimal("0.1") == 0.1) # False (because float 0.1 is not exactly 0.1)
print(Decimal("0.5") == 0.5) # True (0.5 is exactly representable in binary)
```

[[programming/python/python]]