| 1 |
"""Utility functions for decimal numbers. |
| 2 |
|
| 3 |
It includes functions for converting floats to decimals with precision handling |
| 4 |
and for stripping trailing zeros from numeric representations. |
| 5 |
""" |
| 6 |
|
| 7 |
# Standard library imports |
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import contextlib |
| 11 |
import decimal |
| 12 |
import math |
| 13 |
|
| 14 |
|
| 15 |
def float2dec(f: float, digits: int = 10) -> decimal.Decimal: |
| 16 |
"""Convert a float to a decimal with specified precision. |
| 17 |
|
| 18 |
If the float has more than the specified number of digits after the |
| 19 |
decimal point, it will be rounded to the nearest integer. |
| 20 |
|
| 21 |
If the float has exactly the specified number of digits after the |
| 22 |
decimal point, it will be rounded to the nearest integer if the last |
| 23 |
digit is 9, and to the nearest integer if the last digit is 0. |
| 24 |
|
| 25 |
Args: |
| 26 |
f (float): The float to convert. |
| 27 |
digits (int): The number of decimal digits to consider. |
| 28 |
Default is 10. |
| 29 |
|
| 30 |
Returns: |
| 31 |
decimal.Decimal: The converted decimal number. |
| 32 |
""" |
| 33 |
parts = str(f).split(".") |
| 34 |
if len(parts) > 1: |
| 35 |
if parts[1][:digits] == "9" * digits: |
| 36 |
f = math.ceil(f) |
| 37 |
elif parts[1][:digits] == "0" * digits: |
| 38 |
f = math.floor(f) |
| 39 |
return decimal.Decimal(str(f)) |
| 40 |
|
| 41 |
|
| 42 |
def stripzeros(n: float | str | decimal.Decimal) -> decimal.Decimal: |
| 43 |
"""Strip zeros and convert to decimal. |
| 44 |
|
| 45 |
Will always return the shortest decimal representation |
| 46 |
(1.0 becomes 1, 1.234567890 becomes 1.23456789). |
| 47 |
|
| 48 |
Args: |
| 49 |
n (float | str | decimal.Decimal): The number to strip. |
| 50 |
|
| 51 |
Returns: |
| 52 |
decimal.Decimal: The stripped number. |
| 53 |
""" |
| 54 |
n = f"{n:.10f}" if isinstance(n, (float, int)) else str(n) |
| 55 |
if "." in n: |
| 56 |
n = n.rstrip("0").rstrip(".") |
| 57 |
with contextlib.suppress(decimal.InvalidOperation): |
| 58 |
n = decimal.Decimal(n) |
| 59 |
return n |