Skip to main content

Decimal

Struct Decimal 

Source
pub struct Decimal { /* private fields */ }
Expand description

An exact fixed-point decimal: mantissa × 10⁻ˢᶜᵃˡᵉ.

See the module documentation for why the type exists and what it guarantees. Construct with Decimal::new or by parsing the digits:

use chronix_core::Decimal;

let register: Decimal = "1234.5678".parse().unwrap();
assert_eq!(register.mantissa(), 12_345_678);
assert_eq!(register.scale(), 4);
assert_eq!(register.to_string(), "1234.5678");

// Widening is exact; narrowing past a non-zero digit is refused.
assert_eq!(register.rescale(6).unwrap().to_string(), "1234.567800");
assert!(register.rescale(2).is_err());

Implementations§

Source§

impl Decimal

Source

pub const fn new(mantissa: i128, scale: u8) -> Result<Self, DecimalError>

Construct from an unscaled mantissa and a scale.

§Errors

DecimalError::ScaleTooLarge if scale > MAX_DECIMAL_SCALE, and DecimalError::PrecisionOverflow if the mantissa needs more than 38 significant digits.

Source

pub const fn zero(scale: u8) -> Result<Self, DecimalError>

Zero at the given scale.

§Errors

DecimalError::ScaleTooLarge if scale > MAX_DECIMAL_SCALE.

Source

pub const fn mantissa(&self) -> i128

The unscaled integer value.

Source

pub const fn scale(&self) -> u8

The number of digits after the decimal point.

Source

pub const fn is_zero(&self) -> bool

true when the value is exactly zero, at any scale.

Source

pub const fn signum(&self) -> i8

-1, 0 or 1 — the sign of the value.

Source

pub const fn abs(&self) -> Self

The absolute value, at the same scale.

Total: |mantissa| cannot overflow because the mantissa is bounded by MAX_DECIMAL_MANTISSA, well inside i128::MIN.

Source

pub const fn neg(&self) -> Self

The negation, at the same scale.

Source

pub fn rescale(&self, target: u8) -> Result<Self, DecimalError>

Return the same value expressed at target scale.

Widening multiplies by a power of ten and is always exact. Narrowing succeeds only when every digit it would drop is a zero — 1.500 to scale 1 is 1.5, 1.55 to scale 1 is an error, never 1.6 and never 1.5.

§Errors
Source

pub fn normalized(&self, min_scale: u8) -> Self

Drop trailing fractional zeros, down to min_scale.

1.2500 normalised to a minimum scale of 0 is 1.25; to a minimum of 3 it is 1.250. Never changes the value.

Source

pub fn checked_add(&self, other: &Self) -> Result<Self, DecimalError>

Exact sum, at the wider of the two scales.

§Errors

DecimalError::Overflow if the result needs more than 38 significant digits.

Source

pub fn checked_sub(&self, other: &Self) -> Result<Self, DecimalError>

Exact difference, at the wider of the two scales.

§Errors

DecimalError::Overflow if the result needs more than 38 significant digits.

Source

pub fn to_f64_lossy(&self) -> f64

The value as an f64 — lossy, and named so at every call site.

The only conversion to binary floating point this type offers. A settlement quantity must not travel this way; a chart of one may.

Source

pub fn cmp_exact(&self, other: &Self) -> Ordering

Compare against another decimal of any scale, exactly.

Aligning two mantissas at different scales can overflow i128 — 10³⁷ at scale 0 against anything at scale 38 does. An overflow is not an error here but an answer: the side that cannot be represented at the common scale is the side with the larger magnitude, because the other one is representable there.

Trait Implementations§

Source§

impl Clone for Decimal

Source§

fn clone(&self) -> Decimal

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 Decimal

Source§

impl Debug for Decimal

Source§

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

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

impl<'de> Deserialize<'de> for Decimal

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 Decimal

Source§

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

Render the exact digits: no exponent, no rounding, no f64.

Source§

impl Eq for Decimal

Source§

impl From<Decimal> for FieldValue

Source§

fn from(v: Decimal) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Decimal

Source§

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

Parse the digits themselves — never via f64.

Accepts an optional sign, digits with an optional fractional part, and an optional decimal exponent (1.5e3). The scale is the number of fractional digits less the exponent; a literal that lands on a scale above MAX_DECIMAL_SCALE is accepted only if the excess digits are trailing zeros that can be dropped without changing the value.

Source§

type Err = DecimalError

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

impl Hash for Decimal

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 Ord for Decimal

Source§

fn cmp(&self, other: &Self) -> 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 Decimal

Source§

fn eq(&self, other: &Decimal) -> 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 Decimal

Source§

fn partial_cmp(&self, other: &Self) -> 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 Decimal

Source§

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

Exact in both directions: the digits as a string for JSON and any other human-readable format, the (mantissa, scale) pair for postcard and the rest of the binary ones.

A decimal must never reach JSON as a JSON number: serde_json parses one back through f64, which is the loss this type exists to prevent.

Source§

impl StructuralPartialEq for Decimal

Source§

impl TryFrom<Decimal> for Decimal

Source§

type Error = DecimalError

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

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

Performs the conversion.
Source§

impl TryFrom<Decimal> for Decimal

Source§

type Error = DecimalError

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

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

Performs the conversion.
Source§

impl TryFrom<i64> for Decimal

Source§

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

An integer is a decimal of scale 0.

Source§

type Error = DecimalError

The type returned in the event of a conversion error.

Auto Trait Implementations§

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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more