GitHub

big_decimal

API reference for big_decimal.

Arbitrary-precision decimals (Effect's BigDecimal): an int value and a scale, the number being value * 10 ** -scale::

d = big_decimal.from_string_unsafe("123.4500")
d.format()                        # "123.45"
d.divide_unsafe(BigDecimal(3, 0))  # 100 significant digits, rounded half up
d.round(scale=1, mode="half-even")

decimal.Decimal rounds every result to its context's precision (28 digits by default) and keeps signed zeros and exponents apart; a BigDecimal is exact for +, - and *, divides to 100 significant digits as Effect does, and == / hash / < compare values (2 equals 2.00). The scale is any integer from -(2**53 - 1) to 2**53 - 1.

Values

AttributeTypeDescription
MAX_DIGITSLiteral[30000] = 30000

The most significant digits from_string (and so S.BigDecimal and S.BigDecimalFromString) reads by default: converting and printing a longer run costs superlinear time. Arithmetic aligns at most 20,000 digits of scale and a fraction has at most 10,000, so every value arithmetic produces reads back.

Types

TypeDefinitionDescription
RoundingModetype RoundingMode = Literal['ceil', 'floor', 'to-zero', 'from-zero', 'half-ceil', 'half-floor', 'half-to-zero', 'half-from-zero', 'half-even', 'half-odd']

Classes

Functions

round_terminal

round_terminal(n) -> int

1 when the leading digit of n is 5 or more, else 0.

ParameterTypeDescription
nint

Returns int

def round_terminal(n: int) -> int:
    """``1`` when the leading digit of ``n`` is 5 or more, else ``0``."""
    return 0 if int_text(abs(n))[0] < "5" else 1

make

make(value, scale) -> BigDecimal

value * 10 ** -scale; raises ValueError for a scale past 2**53 - 1 either way.

ParameterTypeDescription
valueint
scaleint

Returns BigDecimal

def make(value: int, scale: int) -> BigDecimal:
    """``value * 10 ** -scale``; raises ``ValueError`` for a scale past
    ``2**53 - 1`` either way."""
    return BigDecimal(value, scale)

make_normalized_unsafe

make_normalized_unsafe(value, scale) -> BigDecimal

A BigDecimal already normalized; raises ValueError when value ends in a zero.

ParameterTypeDescription
valueint
scaleint

Returns BigDecimal

def make_normalized_unsafe(value: int, scale: int) -> BigDecimal:
    """A ``BigDecimal`` already normalized; raises ``ValueError`` when
    ``value`` ends in a zero."""
    if value != 0 and value % 10 == 0:
        raise ValueError("Value must be normalized")
    _check_scale(scale)
    return _normalized(value, scale)

from_big_int

from_big_int(n) -> BigDecimal
ParameterTypeDescription
nint

Returns BigDecimal

def from_big_int(n: int) -> BigDecimal:
    return BigDecimal(n, 0)

from_number

from_number(n) -> BigDecimal | None

The decimal JavaScript prints for n (0.1 is 0.1, not the binary fraction); None for NaN and the infinities.

ParameterTypeDescription
nfloat

Returns BigDecimal | None

def from_number(n: float) -> BigDecimal | None:
    """The decimal JavaScript prints for ``n`` (``0.1`` is ``0.1``, not the
    binary fraction); ``None`` for NaN and the infinities."""
    if isinstance(n, int):
        return from_big_int(n)
    if not math.isfinite(n):
        return None
    text = js_number(n)
    if "e" in text:
        return from_string(text)
    lead, _, trail = text.partition(".")
    return BigDecimal(to_int(lead + trail), len(trail))

from_number_unsafe

from_number_unsafe(n) -> BigDecimal

from_number; raises ValueError for a non-finite n.

ParameterTypeDescription
nfloat

Returns BigDecimal

def from_number_unsafe(n: float) -> BigDecimal:
    """``from_number``; raises ``ValueError`` for a non-finite ``n``."""
    out = from_number(n)
    if out is None:
        raise ValueError(f"Number must be finite, got {js_number(n)}")
    return out

from_string

from_string(text, *, max_digits=MAX_DIGITS) -> BigDecimal | None

[+-]digits[.digits][e[+-]digits] ("" is zero); None for anything else, more than max_digits significant digits, a scale past 10,000 or a normalized scale below -10,000.

ParameterTypeDescription
textstr
max_digitsint = MAX_DIGITS

Returns BigDecimal | None

def from_string(text: str, *, max_digits: int = MAX_DIGITS) -> BigDecimal | None:
    """``[+-]digits[.digits][e[+-]digits]`` (``""`` is zero); ``None`` for
    anything else, more than ``max_digits`` significant digits, a scale past
    10,000 or a normalized scale below -10,000."""
    if text == "":
        return _ZERO
    split = _split_exponent(text)
    coefficient = None if split is None else _coefficient(split[0], max_digits)
    if split is None or coefficient is None:
        return None
    value, fraction, digits = coefficient
    scale = len(fraction) - split[1]
    # The normalized scale keeps ``format``'s output parseable.
    normalized_scale = scale if value == 0 else scale - (len(digits) - len(digits.rstrip("0")))
    if scale > _MAX_SCALE or normalized_scale < -_MAX_SCALE:
        return None
    return BigDecimal(value, scale)

from_string_unsafe

from_string_unsafe(text) -> BigDecimal

from_string; raises ValueError for an invalid string.

ParameterTypeDescription
textstr

Returns BigDecimal

def from_string_unsafe(text: str) -> BigDecimal:
    """``from_string``; raises ``ValueError`` for an invalid string."""
    out = from_string(text)
    if out is None:
        raise ValueError(f"Invalid numerical string: {text}")
    return out

sum_all

sum_all(values) -> BigDecimal
ParameterTypeDescription
valuesIterable[BigDecimal]

Returns BigDecimal

def sum_all(values: Iterable[BigDecimal]) -> BigDecimal:
    out = _ZERO
    for n in values:
        out = out.sum(n)
    return out

multiply_all

multiply_all(values) -> BigDecimal
ParameterTypeDescription
valuesIterable[BigDecimal]

Returns BigDecimal

def multiply_all(values: Iterable[BigDecimal]) -> BigDecimal:
    out = _ONE
    for n in values:
        if n.value == 0:
            return _ZERO
        out = out.multiply(n)
    return out