Skip to content

Commit

Permalink
Create decimal_quantize.md
Browse files Browse the repository at this point in the history
  • Loading branch information
williln authored Jul 5, 2024
1 parent 59e33b1 commit 3f81820
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions python/decimal_quantize.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Using `Decimal.quantize`

## Links

- [decimal — Decimal fixed point and floating point arithmetic — Python 3.12.4 documentation](https://docs.python.org/3/library/decimal.html)

## `quantize`

From the docs:

> The quantize() method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places:
```python
from decimal import Decimal

Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')

Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')
```

## Notes

You have to call `quantize` on a `Decimal` object. You also pass it another `Decimal` object. The number of decimal places in the `Decimal` you pass to `quantize` determines the number of decimal places in your result.

To use this with money, you might have something like:

```python
>>> from decimal import Decimal
>>> Decimal(1989)
Decimal('1989')
>>> Decimal(1989).quantize(Decimal("00"))
Decimal('1989')
>>> Decimal(1989).quantize(Decimal(".00"))
Decimal('1989.00')
>>> Decimal(19.89).quantize(Decimal(".00"))
Decimal('19.89')
>>> Decimal(19.89).quantize(Decimal(".013"))
Decimal('19.890')
```

I don't love working with Decimals. But needs must, and discovering `quantize` was nice.

0 comments on commit 3f81820

Please sign in to comment.