Decimal class

Exact constructors

class Decimal
Decimal()

Default constructor. The value is initialized to a signaling NaN.

Decimal(const Decimal &other)

Exact construction by copying the argument.

Decimal(const Decimal &&other)

Exact construction by moving the argument. The argument is reset to a signaling NaN, so it is still in a valid state.

Decimal(const T &other)

Exact integer conversions. T is one of:

int8_t uint8_t
int16_t uint16_t
int32_t uint32_t
int64_t uint64_t
signed char unsigned char
short unsigned short
int unsigned int
long unsigned long
long long unsigned long long

Since construction is always exact, it is safe to allow implicit conversions.

explicit Decimal(const char *const s)

Exact conversion from a C string. If an internal limit is exceeded (e.g. the exponent exceeds MAX_EMAX), InvalidOperation is set and the result is NaN.

Raises ValueError if the argument is NULL.

explicit Decimal(const std::string &s)

Exact conversion from a std::string. If an internal limit is exceeded (e.g. the exponent exceeds MAX_EMAX), InvalidOperation is set and the result is NaN.

explicit Decimal(const mpd_uint128_triple_t &triple)

Exact conversion from an mpd_uint128_triple_t. The triple can represent Decimals with a coefficient up to 38 decimal digits. Refer to the libmpdec documentation for details (See: mpd_from_uint128_triple).

Raises InvalidOperation for invalid input and MemoryError for allocation failures.

Inexact constructors

explicit Decimal(const Decimal &other, Context &c)

Inexact construction according to the context.

explicit Decimal(const T &other, Context &c)

Inexact integer conversions according to the context. T is one of:

int8_t uint8_t
int16_t uint16_t
int32_t uint32_t
int64_t uint64_t
signed char unsigned char
short unsigned short
int unsigned int
long unsigned long
long long unsigned long long
explicit Decimal(const char *const s, Context &c)

Inexact conversion from a C string according to the context. If an internal limit is exceeded (e.g. the exponent exceeds MAX_EMAX), InvalidOperation is set and the result is NaN.

Raises ValueError if the argument is NULL.

explicit Decimal(const std::string &s, Context &c)

Inexact conversion from a std::string according to the context. If an internal limit is exceeded (e.g. the exponent exceeds MAX_EMAX), InvalidOperation is set and the result is NaN.

Accessors

mpd_t *get()

Return a pointer to the private mpd_t. This should only be used for passing a Decimal’s internal value to libmpdec functions, where the Decimal is in the output position.

This is an advanced function that is not necessary for normal use.

const mpd_t *getconst() const

Return a const pointer to the private mpd_t. This should only be used for passing a Decimal’s internal value to libmpdec functions, where the Decimal is in the input position.

This is an advanced function that is not necessary for normal use.

int sign() const

Return the arithmetic sign of the Decimal: 1 for positive values, -1 for negative values.

Decimal coeff() const

Return the coefficient of the Decimal. If the Decimal is a special value, raise ValueError.

int64_t exponent() const

Return the exponent of the Decimal. If the Decimal is a special value, raise ValueError.

Decimal payload() const

Return the NaN payload of the Decimal. The default value for NaNs without a payload is 0.

If the Decimal is not a NaN, raise ValueError.

Exact assignment operators

Decimal &operator=(const Decimal &other)

Make an exact copy of the argument. This function can raise MallocError if self is an arbitrary precision Decimal with a very large coefficient. In practice this does not occur with regular context precisions from 9 to 38 digits.

Copying has a strong exception guarantee, so the lvalue is unchanged in case of MallocError.

Decimal &operator=(Decimal &&other) noexcept

Move the argument. The argument is reset to sNaN and is still in a valid state.

Inexact assignment operators

Decimal &operator+=(const Decimal &other)

In-place add. Uses the thread local context.

Decimal &operator-=(const Decimal &other)

In-place subtract. Uses the thread local context.

Decimal &operator*=(const Decimal &other)

In-place multiply. Uses the thread local context.

Decimal &operator/=(const Decimal &other)

In-place divide. Uses the thread local context.

Decimal &operator%=(const Decimal &other)

In-place remainder. Uses the thread local context.

Exact comparison operators

bool operator==(const Decimal &other) const

Determine if the values are exactly equal. Infinities compare equal if the signs are equal. Quiet NaNs are not equal to anything else (including quiet NaNs).

Signaling NaNs set InvalidOperation, using the thread local context.

bool operator!=(const Decimal &other) const

Determine if the values are not equal. The above rules apply (adapted for !=).

bool operator<(const Decimal &other) const

Determine if self < other. In the case of ordering comparisons quiet NaNs also set InvalidOperation.

bool operator<=(const Decimal &other) const

Determine if self <= other. In the case of ordering comparisons quiet NaNs also set InvalidOperation.

bool operator>=(const Decimal &other) const

Determine if self >= other. In the case of ordering comparisons quiet NaNs also set InvalidOperation.

bool operator>(const Decimal &other) const

Determine if self > other. In the case of ordering comparisons quiet NaNs also set InvalidOperation.

Exact reverse comparison operators

Reverse comparison operators. T is one of:

int8_t uint8_t
int16_t uint16_t
int32_t uint32_t
int64_t uint64_t
signed char unsigned char
short unsigned short
int unsigned int
long unsigned long
long long unsigned long long
bool operator==(const T &other, const Decimal &self)
bool operator!=(const T &other, const Decimal &self)
bool operator<(const T &other, const Decimal &self)
bool operator<=(const T &other, const Decimal &self)
bool operator>=(const T &other, const Decimal &self)
bool operator>(const T &other, const Decimal &self)

Unary arithmetic operators

Decimal operator-() const

Negate the input operand. This function is equivalent to Decimal.minus and applies the thread local context. Note that positive zeros keep their sign, unless the rounding is set to ROUND_FLOOR.

Decimal operator+() const

Return the input operand after applying the thread local context. This function is equivalent to Decimal.plus. Note that negative zeros lose their sign, unless the rounding is set to ROUND_FLOOR.

Binary arithmetic operators

Decimal operator+(const Decimal &other) const

Return self + other. The operation is performed on the unrounded input operands and has a single final rounding step. The thread local context is used.

Same as self.add(other, context).

Decimal operator-(const Decimal &other) const

Return self - other. The operation is performed on the unrounded input operands and has a single final rounding step. The thread local context is used.

Same as self.sub(other, context).

Decimal operator*(const Decimal &other) const

Return self * other. The operation is performed on the unrounded input operands and has a single final rounding step. The thread local context is used.

Same as self.mul(other, context).

Decimal operator/(const Decimal &other) const

Return self / other. The operation is performed on the unrounded input operands and has a single final rounding step. The thread local context is used.

Same as self.div(other, context).

Decimal operator%(const Decimal &other) const

Return self % other. The operation is performed on the unrounded input operands and has a single final rounding step. The thread local context is used.

Same as self.rem(other, context).

Reverse binary arithmetic operators

Reverse binary arithmetic operators. T is one of:

int8_t uint8_t
int16_t uint16_t
int32_t uint32_t
int64_t uint64_t
signed char unsigned char
short unsigned short
int unsigned int
long unsigned long
long long unsigned long long
Decimal operator+(const T &other, const Decimal &self)
Decimal operator-(const T &other, const Decimal &self)
Decimal operator*(const T &other, const Decimal &self)
Decimal operator/(const T &other, const Decimal &self)
Decimal operator%(const T &other, const Decimal &self)

Predicates

bool isfinite() const

Return true if self is a finite number, and false if self is infinite or a quiet or signaling NaN.

bool isinfinite() const

Return true if self is either a positive or negative infinity and false otherwise.

bool isspecial() const

Return true if self is a quiet or signaling NaN or infinite, false otherwise.

bool isnan() const

Return true if self is a quiet or signaling NaN and false otherwise.

bool isqnan() const

Return true if self is a quiet NaN, and false otherwise.

bool issnan() const

Return true if self is a signaling NaN and false otherwise.

bool issigned() const

Return true if self has a negative sign and false otherwise. Note that both zeros and NaNs can carry signs.

bool iszero() const

Return true if self is a positive or negative zero, false otherwise.

bool isinteger() const

Determine whether self is an integer. The exponent of an integer is not necessarily zero and may be negative if the coefficient has trailing zeros.

Predicates with an optional context argument

bool isnormal(const Context &c = context)

Return true if self is a normal finite non-zero number with an adjusted exponent greater than or equal to emin. Return false if self is zero, subnormal, infinite or a quiet or signaling NaN.

bool issubnormal(const Context &c = context)

Return true if self is subnormal, and false otherwise. A number is subnormal if it is non-zero, finite, and has an adjusted exponent less than emin.

Unary functions, no context argument

int64_t adjexp() const

Return the adjusted exponent of self. Defined as exp + digits - 1. Raises ValueError for special values.

Decimal copy_abs() const

Return an exact copy of the absolute value of self. In contrast to Decimal.abs, this function does not use the thread local context.

Decimal copy_negate() const

Return an exact copy of the negation of self. In contrast to -self, this function does not use the thread local context.

Unary functions, optional context argument

std::string number_class(Context &c = context)

Return a string describing the class of the operand. The returned value is one of the following ten strings:

  • “-Infinity”, indicating that the operand is negative infinity.
  • “-Normal”, indicating that the operand is a negative normal number.
  • “-Subnormal”, indicating that the operand is negative and subnormal.
  • “-Zero”, indicating that the operand is a negative zero.
  • “+Zero”, indicating that the operand is a positive zero.
  • “+Subnormal”, indicating that the operand is positive and subnormal.
  • “+Normal”, indicating that the operand is a positive normal number.
  • “+Infinity”, indicating that the operand is positive infinity.
  • “NaN”, indicating that the operand is a quiet NaN (Not a Number).
  • “sNaN”, indicating that the operand is a signaling NaN`.
Decimal abs(Context &c = context) const

Return the absolute value of x.

Decimal ceil(Context &c = context) const

Return the ceiling of self. Not part of the standard.

Decimal exp(Context &c = context) const

Return the value of the exponential function e**x at the given number. The function always uses the ROUND_HALF_EVEN mode.

If c.allcr() == 1, the result is always correctly rounded.

Decimal floor(Context &c = context) const

Return the floor of self. Not part of the standard.

Decimal invroot(Context &c = context) const

Return the reciprocal of the square root of self. The function always uses the ROUND_HALF_EVEN mode. Results are not correctly rounded, even if the allcr context field is set to 1. This might change in a future release.

Decimal ln(Context &c = context) const

Return the natural (base e) logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode.

If c.allcr() == 1, the result is always correctly rounded.

Decimal log10(Context &c = context) const

Return the base ten logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode.

If c.allcr() == 1, the result is always correctly rounded.

Decimal logb(Context &c = context) const

For a non-zero number, return the adjusted exponent of the operand as a Decimal instance. If the operand is a zero, then Decimal(“-Infinity”) is returned and the DivisionByZero condition is raised. If the operand is an infinity then Decimal(“Infinity”) is returned.

Decimal minus(Context &c = context) const

Negate the input operand and apply the context. Note that positive zeros keep their sign, unless the rounding is set to ROUND_FLOOR.

Decimal next_minus(Context &c = context) const

Return the largest number representable in the given context that is smaller than the given operand.

Decimal next_plus(Context &c = context) const

Return the smallest number representable in the given context that is larger than the given operand.

Decimal plus(Context &c = context) const

Copy the input operand and apply the context. Note that negative zeros lose their sign, unless the rounding is set to ROUND_FLOOR.

Decimal reduce(Context &c = context) const

Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal(“0”) to Decimal(“0e0”).

Used for producing representative values for members of an equivalence class. For example, Decimal(“32.100”) and Decimal(“0.321000e+2”) both normalize to the equivalent value Decimal(“32.1”).

Decimal to_integral(Context &c = context) const

Round to the nearest integer without signaling Inexact or Rounded. The rounding mode is determined by the by the given context.

Decimal to_integral_exact(Context &c = context) const

Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used.

Note that the use of exact in this name is determined by the specification and differs from the terminology in libmpdec++.

Decimal sqrt(Context &c = context) const

Return the square root of self to context precision. The rounding mode is always ROUND_HALF_EVEN.

Decimal trunc(Context &c = context) const

Return self, truncated towards zero. Not part of the standard.

Binary functions, no context argument

Decimal compare_total(const Decimal &other) const

Compare two operands using their abstract representation rather than their numerical value. Similar to Decimal.compare, but the result gives a total ordering on Decimal instances. Two Decimal instances with the same numeric value but different representations compare unequal in this ordering:

Decimal("12.0").compare_total(Decimal("12")) == Decimal("-1")

Quiet and signaling NaNs are also included in the total ordering. The result of this function is Decimal(“0”) if both operands have the same representation, Decimal(“-1”) if the first operand is lower in the total order than the second, and Decimal(“1”) if the first operand is higher in the total order than the second operand. See the specification for details of the total order.

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.

Decimal compare_total_mag(const Decimal &other) const

Compare two operands using their abstract representation rather than their value as in Decimal.compare_total, but ignoring the sign of each operand.

x.compare_total_mag(y) == x.copy_abs().compare_total(y.copy_abs())

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.

Binary functions, optional context argument

Decimal add(const Decimal &other, Context &c = context) const

Return the sum of self and other.

Decimal div(const Decimal &other, Context &c = context) const

Return self divided by other.

Decimal divint(const Decimal &other, Context &c = context) const

Return self divided by other, truncated to an integer.

Decimal compare(const Decimal &other, Context &c = context) const

Compare self to other. Return a decimal value:

a.issnan() || b.issnan() => InvalidOperation
a.isqnan() || b.isqnan() => Decimal("NaN")
a < b                    => Decimal("-1")
a == b                   => Decimal("0")
a > b                    => Decimal("1")
Decimal compare_signal(const Decimal &other, Context &c = context) const

Compare self to other. Return a decimal value:

a.issnan() || b.issnan() => InvalidOperation
a.isqnan() || b.isqnan() => InvalidOperation
a < b                    => Decimal("-1")
a == b                   => Decimal("0")
a > b                    => Decimal("1")
Decimal max(const Decimal &other, Context &c = context) const

Maximum of self and other. NOTE: If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.

Decimal max_mag(const Decimal &other, Context &c = context) const

Similar to Decimal.max, but the comparison is done using the absolute values of the operands.

Decimal min(const Decimal &other, Context &c = context) const

Minimum of self and other. NOTE: If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.

Decimal min_mag(const Decimal &other, Context &c = context) const

Similar to Decimal.min, but the comparison is done using the absolute values of the operands.

Decimal mul(const Decimal &other, Context &c = context) const

Return the product of self and other.

Decimal next_toward(const Decimal &other, Context &c = context) const

If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.

Decimal pow(const Decimal &other, Context &c = context) const

Compute self raised to the power of other. If self is negative, then other must be integral. The result will be inexact unless self is integral and the result is finite and can be expressed exactly in prec digits.

The result is almost always correctly rounded, but correct rounding is not guaranteed even if c.allcr() is set.

Decimal quantize(const Decimal &other, Context &c = context) const

Return a value equal to self after rounding and having the exponent of the second operand.

Decimal("1.41421356").quantize(Decimal("1.000")) == Decimal("1.414")

Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then InvalidOperation is set.

This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.

Also unlike other operations, quantize never sets Underflow, even if the result is subnormal and inexact.

If the exponent of the second operand is larger than that of the first, then rounding may be necessary. In this case, the rounding mode is determined by the the given context argument.

Decimal rem(const Decimal &other, Context &c = context) const

The remainder from the division by Decimal.divint. Fails under the same conditions as Decimal.divint.

Decimal rem_near(const Decimal &other, Context &c = context) const

Return self - other * n, where n is the integer nearest the exact value of self / other. If the result is 0 then its sign will be the sign of self.

Decimal scaleb(const Decimal &other, Context &c = context) const

Return the self with the exponent adjusted by the value of other. Equivalently, return the first operand multiplied by 10 ** other. The second operand must be an integer.

Decimal sub(const Decimal &other, Context &c = context) const

Return the difference between self and other.

Binary functions, two return values

std::pair<Decimal, Decimal> divmod(const Decimal &other, Context &c = context) const

Return quotient and remainder of the division self / other.

Ternary functions

Decimal fma(const Decimal &other, const Decimal &third, Context &c = context) const

Fused multiply-add. Return self * other + third with no rounding of the intermediate product self * other.

Decimal(2).fma(3, 5) == Decimal(11)
Decimal powmod(const Decimal &other, const Decimal &third, Context &c = context) const

self ** other % third. The following restrictions hold:

  • All three arguments must be integral.
  • other must be nonnegative.
  • At least one of self or other must be nonzero.
  • third must be nonzero and less than 10 ** prec in absolute value.

Irregular functions

Decimal apply(Context &c = context) const

Return a copy of self with the given context applied. This directly wraps mpd_finalize. It is very similar to Decimal.plus, but does not have special rules for zeros.

int cmp(const Decimal &other) const

Same as Decimal.compare_signal, but with an integer return value. Return INT_MAX if any operand is NaN. Not part of the specification.

int cmp_total(const Decimal &other) const

Same as Decimal.compare_total, but with an integer return value. Not part of the specification.

int cmp_total_mag(const Decimal &other) const

Same as Decimal.compare_total_mag, but with an integer return value. Not part of the specification.

Decimal copy_sign(const Decimal &other) const

Return a copy of the first operand with the sign set to be the same as the sign of the second operand. For example:

Decimal("2.3").copy_sign(Decimal("-1.5")) == Decimal("-2.3")
Decimal rescale(const int64_t exp, Context &c = context) const

Return the number that is equal in value to self, but has the exponent exp. Special numbers are copied without signaling. This function is not part of the standard. It is also not equivalent to the rescale function that was removed from the standard.

bool same_quantum(const Decimal &other) const

Test whether self and other have the same exponent or whether both are NaN.

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.

Decimal shiftl(const int64_t n, Context &c = context) const

Return a copy of self, with its coefficient shifted by n places to the left. self must not be a special number. Digits are never discarded, so the coefficient of the result might exceed prec.

This function is not part of the specification.

Decimal shiftr(const int64_t n, Context &c = context) const

Return a copy of self, with its coefficient shifted by n places to the right.

This function is not part of the specification.

static Decimal exact(const char *const s, Context &c)

This constructs an exact decimal from a C string. The context is only passed for error reporting in case the internal limits are exceeded.

This is a convenience function that is rarely used. Not part of the specification.

static Decimal exact(const std::string &s, Context &c)

Same as above, except for the argument type.

static Decimal ln10(int64_t n, Context &c = context)

Compute ln(10) to n digits of precision. Rounding is always ROUND_HALF_EVEN.

If c.allcr() is set, the result is correctly rounded.

Exact integer conversion

int64_t i64() const

Convert a Decimal that is exactly representable as an int64_t. In case of failure, raise ValueError.

int32_t i32() const

Convert a Decimal that is exactly representable as an int32_t. In case of failure, raise ValueError.

uint64_t u64() const

Convert a Decimal that is exactly representable as a uint64_t. In case of failure, raise ValueError.

uint32_t u32() const

Convert a Decimal that is exactly representable as a uint32_t. In case of failure, raise ValueError.

Exact triple conversion

mpd_uint128_triple_t as_uint128_triple() const

Exact conversion to an mpd_uint128_triple_t. The triple can represent Decimals with a coefficient up to 38 decimal digits. Refer to the libmpdec documentation for details on how to handle the return value and errors (See: mpd_as_uint128_triple).

Raises InvalidOperation if the coefficient is too large.

Exact string conversion

std::string repr(bool capitals = true) const

Same as Decimal.to_sci, but wrap the string in a constructor.

Decimal("1.234E+100").repr() == "Decimal(\"1.234E+100\")"
std::string to_sci(bool capitals = true) const

Return the scientific string representation of a Decimal. This operation is not context sensitive. If capitals is false, the exponent character is lower case, otherwise it is upper case.

std::string to_eng(bool capitals = true) const

Return the engineering string representation of a Decimal. This operation is not context sensitive. If capitals is false, the exponent character is lower case, otherwise it is upper case.

Inexact string conversion

std::string format(const char *fmt, const Context &c = context) const

Return the string representation of a decimal according to format string fmt. The format string syntax is the same as in Python PEP 3101 (See Standard Format Specifiers) and is quite similar to the syntax used for floating point numbers the C fprintf function. The fill character may be a UTF-8 character, the rest of the format string must be ASCII.

The function raises ValueError for an invalid format string or MallocError in case of an allocation failure.

If the “n” format specifier is used, the function calls localeconv. Depending on the guarantees of the system’s localeconv, this method may require a lock.

All other format specifiers are thread-safe.

std::string format(const std::string &s, const Context &c = context) const

Same as above, using a string argument.

Streams

friend std::ostream &operator<<(std::ostream &os, const Decimal &self)

The conversion uses Decimal.to_sci.

Required by the specification

bool iscanonical() const

Return true. This function is required by the specification, and the representation of Decimals is always canonical.

Decimal canonical() const

Return an exact copy of self. No context is used. Identical to the assignment operator.

Decimal copy() const

Return an exact copy of self. No context is used. Identical to the assignment operator.

Decimal logical_and(const Decimal &other, Context &c = context) const

Digit-wise and of self and other. All digits must be 0 or 1.

Decimal logical_invert(Context &c = context) const

Invert the digits of self. All digits must be 0 or 1.

Decimal logical_or(const Decimal &other, Context &c = context) const

Digit-wise or of self and other. All digits must be 0 or 1.

Decimal logical_xor(const Decimal &other, Context &c = context) const

Digit-wise xor of self and other. All digits must be 0 or 1.

static int32_t radix()

Return 10.

Decimal rotate(const Decimal &other, Context &c = context) const

Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is positive then rotation is to the left; otherwise rotation is to the right The coefficient of the first operand is padded on the left with zeros to length precision if necessary. The sign and exponent of the first operand are unchanged.

Decimal shift(const Decimal &other, Context &c = context) const

Return the result of shifting the digits of the self by an amount specified by the other. other must be an integer in the range -prec through prec. The absolute value of the second operand gives the number of places to shift. If self is positive, then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent are unchanged.

Decimal shiftn(const int64_t n, Context &c = context) const

Like Decimal.shift, only that the number of places is specified by a C integer type rather than a decimal. This function is not part of the specification.