GitHub

BigDecimal

API reference for BigDecimal.

value * 10 ** -scale; the constructor is Effect's make.

Attributes

AttributeTypeDescription
valueint
scaleint

Functions

__init__

__init__(value, scale) -> None
ParameterTypeDescription
valueint
scaleint

normalize

normalize() -> BigDecimal

The same number without trailing zeros in value (0 has scale 0); remembered once computed.

Returns BigDecimal

def normalize(self) -> BigDecimal:
    """The same number without trailing zeros in ``value`` (``0`` has
    scale 0); remembered once computed."""
    if self._normalized is not None:
        return self._normalized
    if self.value == 0:
        out = _ZERO
    else:
        digits = int_text(self.value)
        trailing = len(digits) - len(digits.rstrip("0"))
        out = (
            self
            if trailing == 0
            else _normalized(self.value // 10**trailing, self.scale - trailing)
        )
    object.__setattr__(self, "_normalized", out)
    return out

rescale

rescale(scale) -> BigDecimal

The number at scale, digits beyond it truncated toward zero (Effect's scale).

ParameterTypeDescription
scaleint

Returns BigDecimal

def rescale(self, scale: int) -> BigDecimal:
    """The number at ``scale``, digits beyond it truncated toward zero
    (Effect's ``scale``)."""
    if scale > self.scale:
        return BigDecimal(self.value * _power_of_ten(scale - self.scale), scale)
    if scale < self.scale:
        return BigDecimal(_tdiv(self.value, _power_of_ten(self.scale - scale)), scale)
    return self

format

format() -> str

Plain notation, or exponential when the normalized scale is 16 or more either way.

Returns str

def format(self) -> str:
    """Plain notation, or exponential when the normalized scale is 16 or
    more either way."""
    n = self.normalize()
    if abs(n.scale) >= 16:
        return n.to_exponential()
    negative = n.value < 0
    absolute = int_text(-n.value if negative else n.value)
    if n.scale > 0:
        digits = absolute.rjust(n.scale + 1, "0")
        point = len(digits) - n.scale
        complete = f"{digits[:point]}.{digits[point:]}"
    else:
        complete = absolute + "0" * -n.scale
    return f"-{complete}" if negative else complete

to_exponential

to_exponential() -> str

d[.ddd]e±n, as JavaScript's toExponential().

Returns str

def to_exponential(self) -> str:
    """``d[.ddd]e±n``, as JavaScript's ``toExponential()``."""
    if self.value == 0:
        return "0e+0"
    n = self.normalize()
    digits = int_text(n.value)
    point = 2 if n.value < 0 else 1
    head, tail = digits[:point], digits[point:]
    exp = len(tail) - n.scale
    return f"{head}{'.' + tail if tail else ''}e{'+' if exp >= 0 else ''}{exp}"

to_number_unsafe

to_number_unsafe() -> float

The nearest float (Number(format(n))).

Returns float

def to_number_unsafe(self) -> float:
    """The nearest float (``Number(format(n))``)."""
    return float(self.format())

sign

sign() -> Literal[-1, 0, 1]

Returns Literal[-1, 0, 1]

def sign(self) -> Literal[-1, 0, 1]:
    return _cmp(self.value, 0)

is_integer

is_integer() -> bool

Returns bool

def is_integer(self) -> bool:
    return self.normalize().scale <= 0

is_zero

is_zero() -> bool

Returns bool

def is_zero(self) -> bool:
    return self.value == 0

is_negative

is_negative() -> bool

Returns bool

def is_negative(self) -> bool:
    return self.value < 0

is_positive

is_positive() -> bool

Returns bool

def is_positive(self) -> bool:
    return self.value > 0

sum

sum(that) -> BigDecimal
ParameterTypeDescription
thatBigDecimal

Returns BigDecimal

def sum(self, that: BigDecimal) -> BigDecimal:
    if that.value == 0:
        return self
    if self.value == 0:
        return that
    if self.scale > that.scale:
        return BigDecimal(that.rescale(self.scale).value + self.value, self.scale)
    if self.scale < that.scale:
        return BigDecimal(self.rescale(that.scale).value + that.value, that.scale)
    return BigDecimal(self.value + that.value, self.scale)

subtract

subtract(that) -> BigDecimal
ParameterTypeDescription
thatBigDecimal

Returns BigDecimal

def subtract(self, that: BigDecimal) -> BigDecimal:
    if that.value == 0:
        return self
    if self.value == 0:
        return BigDecimal(-that.value, that.scale)
    if self.scale > that.scale:
        return BigDecimal(self.value - that.rescale(self.scale).value, self.scale)
    if self.scale < that.scale:
        return BigDecimal(self.rescale(that.scale).value - that.value, that.scale)
    return BigDecimal(self.value - that.value, self.scale)

multiply

multiply(that) -> BigDecimal
ParameterTypeDescription
thatBigDecimal

Returns BigDecimal

def multiply(self, that: BigDecimal) -> BigDecimal:
    if self.value == 0 or that.value == 0:
        return _ZERO
    return BigDecimal(self.value * that.value, self.scale + that.scale)

divide

divide(that) -> BigDecimal | None

The quotient to 100 significant digits, the last rounded half up; None for a zero divisor.

ParameterTypeDescription
thatBigDecimal

Returns BigDecimal | None

def divide(self, that: BigDecimal) -> BigDecimal | None:
    """The quotient to 100 significant digits, the last rounded half up;
    ``None`` for a zero divisor."""
    return None if that.value == 0 else self.divide_unsafe(that)

divide_unsafe

divide_unsafe(that) -> BigDecimal

divide; raises ZeroDivisionError for a zero divisor.

ParameterTypeDescription
thatBigDecimal

Returns BigDecimal

def divide_unsafe(self, that: BigDecimal) -> BigDecimal:
    """``divide``; raises ``ZeroDivisionError`` for a zero divisor."""
    if that.value == 0:
        raise ZeroDivisionError("Division by zero")
    if self.value == 0:
        return _ZERO
    scale = self.scale - that.scale
    if self.value == that.value:
        return BigDecimal(1, scale)
    return _divide(self.value, that.value, scale, _DEFAULT_PRECISION)

remainder

remainder(divisor) -> BigDecimal | None

The remainder with the dividend's sign; None for a zero divisor.

ParameterTypeDescription
divisorBigDecimal

Returns BigDecimal | None

def remainder(self, divisor: BigDecimal) -> BigDecimal | None:
    """The remainder with the dividend's sign; ``None`` for a zero divisor."""
    return None if divisor.value == 0 else self.remainder_unsafe(divisor)

remainder_unsafe

remainder_unsafe(divisor) -> BigDecimal
ParameterTypeDescription
divisorBigDecimal

Returns BigDecimal

def remainder_unsafe(self, divisor: BigDecimal) -> BigDecimal:
    if divisor.value == 0:
        raise ZeroDivisionError("Division by zero")
    scale = max(self.scale, divisor.scale)
    return BigDecimal(_trem(self.rescale(scale).value, divisor.rescale(scale).value), scale)

abs

abs() -> BigDecimal

Returns BigDecimal

def abs(self) -> BigDecimal:
    return BigDecimal(-self.value, self.scale) if self.value < 0 else self

negate

negate() -> BigDecimal

Returns BigDecimal

def negate(self) -> BigDecimal:
    return BigDecimal(-self.value, self.scale)

truncate

truncate(scale=0) -> BigDecimal

Digits beyond scale dropped (toward zero).

ParameterTypeDescription
scaleint = 0

Returns BigDecimal

def truncate(self, scale: int = 0) -> BigDecimal:
    """Digits beyond ``scale`` dropped (toward zero)."""
    if self.scale <= scale:
        return self
    return BigDecimal(_tdiv(self.value, _power_of_ten(self.scale - scale)), scale)

ceil

ceil(scale=0) -> BigDecimal
ParameterTypeDescription
scaleint = 0

Returns BigDecimal

def ceil(self, scale: int = 0) -> BigDecimal:
    truncated = self.truncate(scale)
    if self.value > 0 and truncated < self:
        return truncated.sum(BigDecimal(1, scale))
    return truncated

floor

floor(scale=0) -> BigDecimal
ParameterTypeDescription
scaleint = 0

Returns BigDecimal

def floor(self, scale: int = 0) -> BigDecimal:
    truncated = self.truncate(scale)
    if self.value < 0 and truncated > self:
        return truncated.sum(BigDecimal(-1, scale))
    return truncated

digit_at

digit_at(scale) -> int

The digit at scale (0 the units, 1 the tenths, -1 the tens), negative for a negative number.

ParameterTypeDescription
scaleint

Returns int

def digit_at(self, scale: int) -> int:
    """The digit at ``scale`` (0 the units, 1 the tenths, -1 the tens),
    negative for a negative number."""
    if self.scale < scale:
        return 0
    return _trem(_tdiv(self.value, _power_of_ten(self.scale - scale)), 10)

round

round(*, scale=0, mode='half-from-zero') -> BigDecimal

Rounded to scale digits by mode.

ParameterTypeDescription
scaleint = 0
modeRoundingMode = 'half-from-zero'

Returns BigDecimal

def round(self, *, scale: int = 0, mode: RoundingMode = "half-from-zero") -> BigDecimal:  # noqa: PLR0911
    """Rounded to ``scale`` digits by ``mode``."""
    if self.scale <= scale:
        return self
    up, down = BigDecimal(5, scale + 1), BigDecimal(-5, scale + 1)
    match mode:
        case "ceil":
            return self.ceil(scale)
        case "floor":
            return self.floor(scale)
        case "to-zero":
            return self.truncate(scale)
        case "from-zero":
            return self.ceil(scale) if self.value > 0 else self.floor(scale)
        case "half-ceil":
            return self.sum(up).floor(scale)
        case "half-floor":
            return self.sum(down).ceil(scale)
        case "half-to-zero":
            return self.sum(up).floor(scale) if self.value < 0 else self.sum(down).ceil(scale)
        case "half-from-zero":
            return self.sum(down).ceil(scale) if self.value < 0 else self.sum(up).floor(scale)
        case "half-even" | "half-odd":
            half_ceil, half_floor = self.sum(up).floor(scale), self.sum(down).ceil(scale)
            if half_ceil == half_floor:
                return half_ceil
            even = _trem(half_ceil.digit_at(scale), 2) == 0
            return half_ceil if even == (mode == "half-even") else half_floor

compare

compare(that) -> Literal[-1, 0, 1]

Effect's Order: -1, 0 or 1.

ParameterTypeDescription
thatBigDecimal

Returns Literal[-1, 0, 1]

def compare(self, that: BigDecimal) -> Literal[-1, 0, 1]:
    """Effect's ``Order``: ``-1``, ``0`` or ``1``."""
    if self.scale == that.scale:
        return _cmp(self.value, that.value)
    mine, theirs = self.sign(), that.sign()
    if mine != theirs:
        return -1 if mine < theirs else 1
    if mine == 0:
        return 0
    difference = self.scale - that.scale
    if abs(difference) > _MAX_COMPARISON_SCALE_ALIGNMENT:
        return _magnitude(that, self) if mine == -1 else _magnitude(self, that)
    power = 10 ** abs(difference)
    if difference > 0:
        return _cmp(self.value, that.value * power)
    return _cmp(self.value * power, that.value)

between

between(*, minimum, maximum) -> bool

minimum <= self <= maximum.

ParameterTypeDescription
minimumBigDecimal
maximumBigDecimal

Returns bool

def between(self, *, minimum: BigDecimal, maximum: BigDecimal) -> bool:
    """``minimum <= self <= maximum``."""
    return minimum <= self <= maximum

clamp

clamp(*, minimum, maximum) -> BigDecimal

self held within minimum and maximum.

ParameterTypeDescription
minimumBigDecimal
maximumBigDecimal

Returns BigDecimal

def clamp(self, *, minimum: BigDecimal, maximum: BigDecimal) -> BigDecimal:
    """``self`` held within ``minimum`` and ``maximum``."""
    return min(max(self, minimum), maximum)