pub struct Decimal { /* private fields */ }Expand description
An exact base-10 fixed-point number: an integer coefficient divided by a power
of ten. The value is coefficient · 10^(−scale), so 19.99 is coefficient = 1999, scale = 2. Money lives here — 0.1 + 0.2 is exactly 0.3, never the
0.30000000000000004 of a binary float, and a long ledger of sums never drifts.
+, −, × are exact (multiplication adds the scales); ÷ and Decimal::rescale
round under an explicit RoundingMode because base-10 division need not
terminate. Equality and ordering are by value (1.0 == 1.00 == 1); scale
is only a display hint. The coefficient is a BigInt, so the value is unbounded
and exact — the i128 fast path is the documented performance follow-up.
Implementations§
Source§impl Decimal
impl Decimal
Sourcepub fn from_bigint(coeff: BigInt) -> Decimal
pub fn from_bigint(coeff: BigInt) -> Decimal
The integer coeff at scale 0.
pub fn from_i64(x: i64) -> Decimal
Sourcepub fn from_coeff_scale(coeff: BigInt, scale: u32) -> Decimal
pub fn from_coeff_scale(coeff: BigInt, scale: u32) -> Decimal
Construct directly from a coefficient and scale (value = coeff / 10^scale).
pub fn zero() -> Decimal
pub fn one() -> Decimal
pub fn scale(&self) -> u32
pub fn coefficient(&self) -> &BigInt
pub fn is_zero(&self) -> bool
pub fn is_negative(&self) -> bool
pub fn negated(&self) -> Decimal
pub fn abs(&self) -> Decimal
Sourcepub fn to_rational(&self) -> Rational
pub fn to_rational(&self) -> Rational
Exact view as a Rational (coeff / 10^scale) — lossless, the bridge that
keeps Decimal inside the exact tower.
Sourcepub fn from_rational(
value: &Rational,
scale: u32,
mode: RoundingMode,
) -> Decimal
pub fn from_rational( value: &Rational, scale: u32, mode: RoundingMode, ) -> Decimal
The fixed-point value nearest value at the given scale, rounded under mode.
Sourcepub fn rescale(&self, scale: u32, mode: RoundingMode) -> Decimal
pub fn rescale(&self, scale: u32, mode: RoundingMode) -> Decimal
Restate at a different scale. Widening appends zeros (exact); narrowing drops
digits and rounds under mode.
pub fn add(&self, other: &Decimal) -> Decimal
pub fn sub(&self, other: &Decimal) -> Decimal
Sourcepub fn mul(&self, other: &Decimal) -> Decimal
pub fn mul(&self, other: &Decimal) -> Decimal
Exact product: coefficients multiply, scales add.
Sourcepub fn div(
&self,
other: &Decimal,
scale: u32,
mode: RoundingMode,
) -> Option<Decimal>
pub fn div( &self, other: &Decimal, scale: u32, mode: RoundingMode, ) -> Option<Decimal>
Quotient rounded to scale under mode. None when other == 0 — base-10
division need not terminate, so the caller names the precision it wants.
Sourcepub fn to_le_bytes(&self) -> (bool, Vec<u8>, u32)
pub fn to_le_bytes(&self) -> (bool, Vec<u8>, u32)
Sign + little-endian coefficient bytes + scale — the wire form (the inverse of
Decimal::from_le_bytes). Reuses BigInt’s exact byte serialization.