Skip to main content

Dec

Struct Dec 

Source
pub struct Dec(/* private fields */);
Expand description

A decimal carrying a fixed Dec::SCALE decimal places, backed by an i128 holding the value scaled by 10^SCALE.

Arithmetic is exact between Dec::MIN and Dec::MAX. Anything that leaves that range becomes Dec::NAN and stays NaN through every later operation, so the fault reaches the boundary where Dec::is_finite is checked rather than being clamped to a plausible number or raised as a panic on a hot path.

The ordering is total: NaN equals itself and sorts below Dec::MIN, which keeps Eq, Ord and Hash derivable and so keeps Dec usable as a BTreeMap or HashMap key. See the design notes for why.

use troy::{Dec, dec};

assert_eq!(dec!(2.5) + dec!(0.25), dec!(2.75));
assert!((Dec::MAX + Dec::ONE).is_nan());

Implementations§

Source§

impl Dec

Source

pub const SCALE: u32 = 18

Number of decimal places every Dec carries.

Source

pub const ZERO: Self

Zero.

Source

pub const ONE: Self

One.

Source

pub const NEG_ONE: Self

Negative one.

Source

pub const MIN: Self

The smallest finite value, -Dec::MAX. The finite range is symmetric, so negation and Dec::abs are total and exact on it.

Source

pub const MAX: Self

The largest finite value, roughly 1.7e20.

Source

pub const EPSILON: Self

The smallest positive value, one unit in the last place.

Source

pub const NAN: Self

The not-a-number state. Every operation that leaves the finite range returns it, and every operation given it returns it, so an invalid result carries its own invalidity to wherever it is finally checked with Dec::is_finite.

Unlike an IEEE NaN this one is ordered and reflexive: it equals itself and sorts below Dec::MIN, which is what keeps Eq and Ord available. It therefore wins any min reduction and sorts to the front of a collection.

use troy::Dec;

assert_eq!(Dec::NAN, Dec::NAN);
assert!(Dec::NAN < Dec::MIN);
assert!(!Dec::NAN.is_finite());
Source

pub const fn from_raw(raw: i128) -> Self

Wrap a raw scaled integer. Total: i128::MIN is Dec::NAN, so every raw round trips through Dec::into_raw.

Source

pub const fn is_nan(self) -> bool

Whether this is Dec::NAN, the state every overflow collapses to.

Source

pub const fn is_finite(self) -> bool

Whether this is an ordinary number, the check to make where a value leaves the system.

use troy::{Dec, dec};

assert!(dec!(1.5).is_finite());
assert!(Dec::MAX.is_finite());
assert!(!(Dec::MAX * Dec::MAX).is_finite());
Source

pub const fn into_raw(self) -> i128

The underlying scaled integer, the inverse of Dec::from_raw.

Source

pub const fn from_int(value: i64) -> Self

An exact whole number. Every i64 fits the finite range.

Source

pub const fn from_u64(value: u64) -> Self

An exact whole number. Every u64 fits the finite range.

Source

pub const fn parse_const(value: &str) -> Option<Self>

Parse in a const context, None on malformed or out-of-range text. The dec! macro wraps this.

Source

pub const fn is_zero(self) -> bool

Whether this is exactly zero. Dec::NAN is not.

Source

pub const fn is_sign_negative(self) -> bool

Whether this is a finite value below zero. Dec::NAN is neither negative nor positive, so this is not a finiteness test.

Source

pub const fn is_sign_positive(self) -> bool

Whether this is a value above zero. Dec::NAN is not.

Source

pub const fn abs(self) -> Self

The magnitude, exact for every finite value because the range is symmetric. Dec::NAN stays NaN.

Source

pub const fn signum(self) -> Self

Dec::ONE, Dec::NEG_ONE or Dec::ZERO by sign. Dec::NAN stays NaN.

Source

pub fn to_f64(self) -> f64

Convert to f64, rounding to the nearest representable double. Dec::NAN becomes f64::NAN.

Source

pub fn from_f64(value: f64) -> Option<Self>

Convert from f64, or None when the value is not finite or does not fit the finite range. This never yields Dec::NAN: a conversion reports failure directly, since there is no earlier computation for a NaN to have propagated from.

Source

pub const fn floor(self) -> Self

The largest whole number at or below this value, or Dec::NAN when that leaves the finite range, as it does for Dec::MIN.

Source

pub const fn ceil(self) -> Self

The smallest whole number at or above this value, or Dec::NAN when that leaves the finite range, as it does for Dec::MAX.

Source

pub const fn trunc(self) -> Self

The whole part, rounding towards zero. Always finite for a finite input; Dec::NAN stays NaN.

Source

pub const fn checked_add(self, rhs: Self) -> Option<Self>

The sum, or None if it leaves the finite range or either side is Dec::NAN. Use this where an overflow should be handled on the spot rather than propagated.

Source

pub const fn checked_sub(self, rhs: Self) -> Option<Self>

The difference, or None if it leaves the finite range or either side is Dec::NAN.

Source

pub fn checked_mul(self, rhs: Self) -> Option<Self>

The product, or None if it leaves the finite range or either side is Dec::NAN. Exact, with the excess below Dec::SCALE rounded half away from zero.

Source

pub fn checked_div(self, rhs: Self) -> Option<Self>

The quotient, or None on division by zero, if it leaves the finite range, or if either side is Dec::NAN.

Source

pub fn saturating_div(self, rhs: Self) -> Self

The quotient, clamped to Dec::MIN or Dec::MAX on overflow. Division by zero has no side to clamp towards and still gives Dec::NAN, as does a NaN operand.

Source

pub fn saturating_mul(self, rhs: Self) -> Self

The product, clamped to Dec::MIN or Dec::MAX on overflow. A Dec::NAN operand still gives NaN: there is no sign to clamp towards, and clamping an unknown would invent one.

Source

pub const fn saturating_add(self, rhs: Self) -> Self

The sum, clamped to Dec::MIN or Dec::MAX on overflow. A Dec::NAN operand still gives NaN.

Source

pub const fn saturating_sub(self, rhs: Self) -> Self

The difference, clamped to Dec::MIN or Dec::MAX on overflow. A Dec::NAN operand still gives NaN.

Source

pub const fn midpoint(self, rhs: Self) -> Self

The value halfway between the two, which cannot overflow because the sum is formed in a wider space. Dec::NAN on either side gives NaN.

Source§

impl Dec

Source

pub fn from_decimal(value: Decimal) -> Option<Self>

Rescale a Decimal, exact unless it carries more than Dec::SCALE decimal places, where the excess rounds half away from zero.

Source

pub fn to_decimal(self) -> Option<Decimal>

Widen to a Decimal at Dec::SCALE decimal places, or None when the value needs more than the 96 bits a Decimal mantissa holds.

Source§

impl Dec

Source

pub fn from_f64_round(value: f64, dp: u32) -> Option<Self>

Dec::from_f64 followed by Dec::round_dp, which is how a float carrying binary representation error is best pinned to a known scale.

Source

pub const fn round_dp(self, dp: u32) -> Self

Round to dp decimal places, halves away from zero. A no-op once dp reaches Dec::SCALE. Returns Dec::NAN when the rounded value leaves the finite range, as it does for Dec::MIN at dp 0, and when the input is already NaN.

use troy::{Dec, dec};

assert_eq!(dec!(2.5).round_dp(0), dec!(3));
assert_eq!(dec!(-2.5).round_dp(0), dec!(-3));
assert!(Dec::MAX.round_dp(0).is_nan());
Source

pub const fn round_to_step(self, step: Self) -> Self

Round to the nearest multiple of step, halves away from zero. A non-positive step is a no-op. Returns Dec::NAN when the result leaves the finite range, and when either side is already NaN.

use troy::dec;

assert_eq!(dec!(104_237.28).round_to_step(dec!(0.25)), dec!(104_237.25));

Trait Implementations§

Source§

impl Add for Dec

The sum, or Dec::NAN on overflow or from a NaN operand. See Dec::checked_add and Dec::saturating_add to handle it on the spot.

Source§

type Output = Dec

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Self) -> Self

Performs the + operation. Read more
Source§

impl AddAssign for Dec

Source§

fn add_assign(&mut self, rhs: Self)

Performs the += operation. Read more
Source§

impl Clone for Dec

Source§

fn clone(&self) -> Dec

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Dec

Source§

impl Debug for Dec

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Dec

Source§

fn default() -> Dec

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Dec

Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Dec

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Div for Dec

The quotient, or Dec::NAN on division by zero, on overflow, or from a NaN operand.

There is no infinity in the type, so dividing by zero has no value to return; it is the same fault as an overflow and collapses to the same NaN, which then carries to wherever the result is examined rather than panicking on a hot path. The quotient is exact at Dec::SCALE places, with a tie rounding half away from zero. Dec::checked_div reports the fault, Dec::saturating_div clamps an overflow.

Source§

type Output = Dec

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Self) -> Self

Performs the / operation. Read more
Source§

impl DivAssign for Dec

Source§

fn div_assign(&mut self, rhs: Self)

Performs the /= operation. Read more
Source§

impl Eq for Dec

Source§

impl From<i32> for Dec

Source§

fn from(value: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Dec

Source§

fn from(value: i64) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for Dec

Source§

fn from(value: u32) -> Self

Converts to this type from the input type.
Source§

impl From<u64> for Dec

Source§

fn from(value: u64) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Dec

Source§

type Err = ParseDecError

The associated error which can be returned from parsing.
Source§

fn from_str(value: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for Dec

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Mul for Dec

The product, or Dec::NAN on overflow or from a NaN operand.

The finite range is +/-1.7e20 and no price, size or notional lives near it, so an overflow here is a bug rather than a number: bad input, or an accumulation that ran away. Saturating would answer it with a plausible looking figure that survives every downstream check, so the operators return NaN instead and carry the fault to wherever the result is finally examined. Dec::checked_mul reports it, Dec::saturating_mul clamps it, for callers who would rather decide on the spot.

Source§

type Output = Dec

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Self) -> Self

Performs the * operation. Read more
Source§

impl MulAssign for Dec

Source§

fn mul_assign(&mut self, rhs: Self)

Performs the *= operation. Read more
Source§

impl Neg for Dec

Negation, which is exact and total: the finite range is symmetric, so every value has a negation, and the NaN pattern is its own.

Source§

type Output = Dec

The resulting type after applying the - operator.
Source§

fn neg(self) -> Self

Performs the unary - operation. Read more
Source§

impl Ord for Dec

Source§

fn cmp(&self, other: &Dec) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for Dec

Source§

fn eq(&self, other: &Dec) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Dec

Source§

fn partial_cmp(&self, other: &Dec) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Dec

Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Dec

Source§

impl Sub for Dec

The difference, or Dec::NAN on overflow or from a NaN operand. See Dec::checked_sub and Dec::saturating_sub to handle it on the spot.

Source§

type Output = Dec

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Self) -> Self

Performs the - operation. Read more
Source§

impl SubAssign for Dec

Source§

fn sub_assign(&mut self, rhs: Self)

Performs the -= operation. Read more
Source§

impl Sum for Dec

Source§

fn sum<I: Iterator<Item = Self>>(iter: I) -> Self

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl<'a> Sum<&'a Dec> for Dec

Source§

fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl TryFrom<Dec> for Decimal

Source§

type Error = ParseDecError

The type returned in the event of a conversion error.
Source§

fn try_from(value: Dec) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<Decimal> for Dec

Source§

type Error = ParseDecError

The type returned in the event of a conversion error.
Source§

fn try_from(value: Decimal) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for Dec

§

impl RefUnwindSafe for Dec

§

impl Send for Dec

§

impl Sync for Dec

§

impl Unpin for Dec

§

impl UnsafeUnpin for Dec

§

impl UnwindSafe for Dec

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.