django_twc_toolbox.numbers

Module Contents

Functions

format_number_no_round

Formats a number with the number of decimal places specified without rounding.

Data

T

API

django_twc_toolbox.numbers.T

‘TypeVar(…)’

django_twc_toolbox.numbers.format_number_no_round(number: django_twc_toolbox.numbers.T, *, decimal_places: int = 2) str | decimal.Decimal

Formats a number with the number of decimal places specified without rounding.

It takes a number and ensures it has at least the number of decimal places passed it as an argument, defaulting to 2. This csn be useful for displaying and working with currency as it does not round the number, preserving any additional precision beyond the decimal places if present.

Args: number (T): The number to format. Can be a float, str, or Decimal. decimal_places (int, optional): Minimum number of decimal places to display. Defaults to 2.

Returns: str | Decimal: The formatted number as a string if the input was a float or str, or as a Decimal if the input was a Decimal.

Raises: ValueError: If the input cannot be converted to a valid number.

Examples: >>> format_number_no_round(123.4) ‘123.40’ >>> format_number_no_round(123.45) ‘123.45’ >>> format_number_no_round(123.456) ‘123.456’ >>> format_number_no_round(123.4560) ‘123.456’ >>> format_number_no_round(123.45600) ‘123.456’ >>> format_number_no_round(123.45600, decimal_places=5) ‘123.45600’ >>> format_number_no_round(Decimal(‘123.4’)) Decimal(‘123.40’)