Skip to main content

Decimal

Struct Decimal 

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

A 128-bit signed fixed-point decimal.

value = mantissa × 10^(-scale)
  • mantissa: signed coefficient stored as i128
  • scale: number of decimal places in [0, MAX_SCALE]

On-chain Borsh encoding: 17 bytes (16-byte LE mantissa + 1-byte scale).

Implementations§

Source§

impl Decimal

Source

pub fn checked_add(self, rhs: Decimal) -> Result<Decimal, ArithmeticError>

Checked addition. Aligns scales then adds mantissas.

Source

pub fn checked_sub(self, rhs: Decimal) -> Result<Decimal, ArithmeticError>

Checked subtraction. Aligns scales then subtracts mantissas.

Source

pub fn checked_mul(self, rhs: Decimal) -> Result<Decimal, ArithmeticError>

Checked multiplication: self * rhs.

Result scale = self.scale + rhs.scale. Returns Err(ScaleExceeded) if that exceeds MAX_SCALE.

Source

pub fn checked_div(self, rhs: Decimal) -> Result<Decimal, ArithmeticError>

Checked division: self / rhs.

Scales the numerator up by MAX_SCALE - self.scale places before dividing to retain maximum precision.

Source

pub fn checked_neg(self) -> Result<Decimal, ArithmeticError>

Negation: returns -self.

Fails with Err(Overflow) for Decimal::MIN (two’s-complement has no positive counterpart for i128::MIN).

Source

pub fn checked_abs(self) -> Result<Decimal, ArithmeticError>

Absolute value: returns |self|.

Fails with Err(Overflow) for Decimal::MIN.

Source

pub fn checked_mul_div( self, numerator: Decimal, denominator: Decimal, ) -> Result<Decimal, ArithmeticError>

Compound (self × numerator) / denominator with 256-bit intermediate.

Prevents silent overflow that occurs when self × numerator exceeds i128::MAX in a naive two-step mul then div.

Source§

impl Decimal

Source

pub fn from_u64(v: u64) -> Self

Create a Decimal with scale 0 from a u64.

Source

pub fn from_i64(v: i64) -> Self

Create a Decimal with scale 0 from an i64.

Source

pub fn from_u128(v: u128) -> Result<Self, ArithmeticError>

Create a Decimal with scale 0 from a u128.

Returns Err(Overflow) if v > i128::MAX.

Source

pub fn from_i128(v: i128) -> Self

Create a Decimal with scale 0 from an i128.

Source

pub fn from_token_amount( amount: u64, decimals: u8, ) -> Result<Self, ArithmeticError>

Create a Decimal from a raw SPL token amount and the mint’s decimals.

from_token_amount(1_500_000, 6) represents 1.500000 USDC.

Source§

impl Decimal

Source

pub fn to_i128_truncated(self) -> i128

Truncate toward zero and return the integer part as i128.

Decimal { mantissa: 157, scale: 2 } (= 1.57) → 1

Source

pub fn to_u64_truncated(self) -> Result<u64, ArithmeticError>

Truncate toward zero and return the integer part as u64.

Returns Err(Overflow) if the value is negative or exceeds u64::MAX.

Source

pub fn to_token_amount( self, decimals: u8, mode: RoundingMode, ) -> Result<u64, ArithmeticError>

Convert to a raw SPL token u64 amount with explicit rounding.

Rounds to decimals decimal places first, then converts to an integer.

Source§

impl Decimal

Source

pub fn from_str_exact(s: &str) -> Result<Self, ArithmeticError>

Parse a decimal string into a Decimal.

Accepted formats:

  • "123"{ mantissa: 123, scale: 0 }
  • "1.23"{ mantissa: 123, scale: 2 }
  • "-1.23"{ mantissa: -123, scale: 2 }
  • "+1.23"{ mantissa: 123, scale: 2 }

Returns Err(ScaleExceeded) if there are more than 28 fractional digits, or Err(InvalidInput) for malformed strings.

Source§

impl Decimal

Source

pub const ZERO: Self

Additive identity: 0 × 10^0.

Source

pub const ONE: Self

Multiplicative identity: 1 × 10^0.

Source

pub const MAX: Self

Maximum representable value: i128::MAX × 10^0.

Source

pub const MIN: Self

Minimum representable value: i128::MIN × 10^0.

Source

pub const NEG_ONE: Self

Negative one: -1 × 10^0.

Source

pub const HUNDRED: Self

100 × 10^0 — useful for percentage arithmetic.

Source

pub const TEN_THOUSAND: Self

10_000 × 10^0 — basis-points denominator.

Source

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

Construct a Decimal from a raw mantissa and scale.

Returns Err(ArithmeticError::ScaleExceeded) if scale > MAX_SCALE.

Source

pub fn mantissa(self) -> i128

Returns the raw mantissa.

Source

pub fn scale(self) -> u8

Returns the scale (number of decimal places).

Source

pub fn is_zero(self) -> bool

Returns true if the value is exactly zero.

Source

pub fn is_positive(self) -> bool

Returns true if the value is strictly positive.

Source

pub fn is_negative(self) -> bool

Returns true if the value is strictly negative.

Source§

impl Decimal

Source

pub fn round(self, dp: u8, mode: RoundingMode) -> Result<Self, ArithmeticError>

Round self to dp decimal places using the given rounding mode.

If dp >= self.scale no rounding is needed and self is returned unchanged (possibly with a different scale representation).

§Errors

Returns Err(ScaleExceeded) if dp > MAX_SCALE.

Source

pub fn rescale_up(self, new_scale: u8) -> Result<Self, ArithmeticError>

Rescale self to a higher number of decimal places by padding zeros.

Only increases scale; use round to decrease it. Returns Err(ScaleExceeded) if new_scale > MAX_SCALE or Err(Overflow) if the mantissa multiplication overflows.

Trait Implementations§

Source§

impl Clone for Decimal

Source§

fn clone(&self) -> Decimal

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Decimal

Source§

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

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

impl Default for Decimal

Source§

fn default() -> Decimal

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

impl Display for Decimal

Source§

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

Formats the value using the given formatter. Read more
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 · Source§

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

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

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

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

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

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

impl PartialEq for Decimal

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
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 · 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 · 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 · 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 · 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 Copy for Decimal

Source§

impl Eq for Decimal

Source§

impl StructuralPartialEq for Decimal

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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.