Skip to main content

Decimal

Struct Decimal 

Source
pub struct Decimal<I: UnderlyingInt>(/* private fields */);
Expand description

The decimal type.

The I is the underlying integer type. It supports u128 only by now, and will support u64 and u32 in next version. They have aliases Dec128, Dec64 and Dec32 respectively.

Implementations§

Source§

impl<I: UnderlyingInt> Decimal<I>

Source

pub fn abs(self) -> Self

Computes the absolute value of self.

Source

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

Computes the addition.

Return None if overflow.

There may loss precision if the scales of the 2 operands differ too greatly. It’s a classic round-off errors. of floating-point calculation.

§Examples:
use lean_decimal::Dec128;
let a = Dec128::from_parts(123, 2); // 1.23
let b = Dec128::from_parts(1, 4);   // 0.0001
let sum = Dec128::from_parts(12301, 4); // 1.2301
assert_eq!(a.checked_add(b).unwrap(), sum);
Source

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

Computes the addition.

Return None if overflow.

There may loss precision if the scales of the 2 operands differ too greatly. It’s a classic round-off errors. of floating-point calculation.

§Examples:
use lean_decimal::Dec128;
let a = Dec128::from_parts(123, 2); // 1.23
let b = Dec128::from_parts(1, 4);   // 0.0001
let diff = Dec128::from_parts(12299, 4); // 1.2299
assert_eq!(a.checked_sub(b).unwrap(), diff);
Source

pub fn checked_mul(self, right: impl Into<Self>) -> Option<Self>

Computes the multiplication.

Return None if overflow.

The right oprand could be short integers or decimals.

§Examples:
use lean_decimal::Dec128;
let a = Dec128::from_parts(123, 2); // 1.23
let b = Dec128::from_parts(1, 4);   // 0.0001
let prod = Dec128::from_parts(123, 6); // 0.000123
assert_eq!(a.checked_mul(b).unwrap(), prod);

// by integer
let prod = Dec128::from_parts(246, 2); // 2.46
assert_eq!(a.checked_mul(2).unwrap(), prod);
Source

pub fn checked_div(self, right: impl Into<Self>) -> Option<Self>

Computes the division.

Return None if overflow or divied by zero.

The right oprand could be short integers or decimals.

§Examples:
use lean_decimal::Dec128;
let a = Dec128::from_parts(123, 2); // 1.23
let b = Dec128::from_parts(1, 4);   // 0.0001
let q = Dec128::from_parts(12300, 0); // 12300
assert_eq!(a.checked_div(b).unwrap(), q);

// by integer
let q = Dec128::from_parts(615, 3); // 0.615
assert_eq!(a.checked_div(2).unwrap(), q);
Source

pub fn round_to(self, dst_scale: u32) -> Self

Round to the @dst_scale. Keep @dst_scale fraction decimal fractions.

Do nothing if the original scale is not bigger than @dst_scale

§Examples:
use lean_decimal::Dec128;
let a = Dec128::from_parts(12345678, 6); // 12.345678
let b = Dec128::from_parts(1235, 2);   // 12.35
assert_eq!(a.round_to(2), b);
Source§

impl<I: UnderlyingInt> Decimal<I>

Source

pub fn is_zero(self) -> bool

Return if the number is zero.

Source

pub fn is_positive(self) -> bool

Return if the number is positive.

Source

pub fn is_negative(self) -> bool

Return if the number is negative.

Source§

impl<I: UnderlyingInt> Decimal<I>

Source

pub const ZERO: Self

Zero.

Source

pub const MAX: Self

The largest value. To be largest, the scale is 0, so this is an integer, 2^b - 1, where b is the mantissa bits, which is 121, 58, 27 for Dec128, Dec64 and Dec32 correspondingly.

Source

pub const MIN: Self

The smallest value. It’s the negative of Self::MAX.

Source

pub fn parts(self) -> (I::Signed, u32)

Deconstruct the decimal into signed mantissa and scale.

§Examples:
use lean_decimal::Dec128;
use core::str::FromStr;

let d = Dec128::from_str("3.14").unwrap();
assert_eq!(d.parts(), (314, 2));
Source

pub fn from_parts<S>(mantissa: S, scale: u32) -> Self
where S: Into<I::Signed>,

Construct a decimal from signed mantissa and scale.

§Panic:

Panic if the mantissa or scale is out of range. Use Self::try_from_parts for the checked version.

§Examples:
use lean_decimal::Dec128;
let d = Dec128::from_parts(314, 2);
assert_eq!(d.to_string(), "3.14");
Source

pub fn try_from_parts<S>(mantissa: S, scale: u32) -> Option<Self>
where S: Into<I::Signed>,

Construct a decimal from signed mantissa and scale.

Return None if the mantissa or scale is out of range.

§Examples:
use lean_decimal::Dec128;
let d = Dec128::try_from_parts(314, 2).unwrap();
assert_eq!(d.to_string(), "3.14");

let d = Dec128::try_from_parts(314, 99); // 99 is out of range
assert!(d.is_none());
Source

pub const fn underlying(self) -> I

Return the underlying integer.

You should not try to decode this integer yourself. You should just hold this and load it later.

Source

pub fn from_underlying(ui: I) -> Self

Load from underlying integer, which should only be got from Self::underlying.

§Panic:

Panic if invalid. Use Self::try_from_underlying for checked version.

Source

pub fn try_from_underlying(ui: I) -> Option<Self>

Load from underlying integer, which should only be got from Self::underlying.

Source

pub const unsafe fn unchecked_from_underlying(ui: I) -> Self

Load from underlying integer, which should only be got from Self::underlying.

SAFETY: It’s safe if you make sure the integer was got from Self::underlying.

Trait Implementations§

Source§

impl<I: UnderlyingInt> Add for Decimal<I>

Source§

type Output = Decimal<I>

The resulting type after applying the + operator.
Source§

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

Performs the + operation. Read more
Source§

impl<I: UnderlyingInt> AddAssign for Decimal<I>

Source§

fn add_assign(&mut self, rhs: Self)

Performs the += operation. Read more
Source§

impl<I: Clone + UnderlyingInt> Clone for Decimal<I>

Source§

fn clone(&self) -> Decimal<I>

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<I: UnderlyingInt> Debug for Decimal<I>

Source§

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

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

impl<I: Default + UnderlyingInt> Default for Decimal<I>

Source§

fn default() -> Decimal<I>

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

impl<I: UnderlyingInt> Display for Decimal<I>

Display the decimal.

It supports some formatting options: width, fill, alignment, precision, sign and 0-fill.

Examples:

use lean_decimal::Dec128;
let d = Dec128::from_parts(12_3470, 4);

assert_eq!(format!("{}", d), "12.3470");
assert_eq!(format!("{:.6}", d), "12.347000"); // set precision: pad 0
assert_eq!(format!("{:.2}", d), "12.35"); // set smaller precision: round the number
assert_eq!(format!("{:x>10}", d), "xxx12.3470"); // set width, fill, alignment
assert_eq!(format!("{:+}", d), "+12.3470"); // set sign
Source§

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

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

impl<I: UnderlyingInt, R: Into<Self>> Div<R> for Decimal<I>

Source§

type Output = Decimal<I>

The resulting type after applying the / operator.
Source§

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

Performs the / operation. Read more
Source§

impl<I: UnderlyingInt, R: Into<Self>> DivAssign<R> for Decimal<I>

Source§

fn div_assign(&mut self, rhs: R)

Performs the /= operation. Read more
Source§

impl From<i16> for Decimal<u128>

Source§

fn from(value: i16) -> Self

Converts to this type from the input type.
Source§

impl From<i32> for Decimal<u128>

Source§

fn from(value: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Decimal<u128>

Source§

fn from(value: i64) -> Self

Converts to this type from the input type.
Source§

impl From<i8> for Decimal<u128>

Source§

fn from(value: i8) -> Self

Converts to this type from the input type.
Source§

impl From<u16> for Decimal<u128>

Source§

fn from(value: u16) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for Decimal<u128>

Source§

fn from(value: u32) -> Self

Converts to this type from the input type.
Source§

impl From<u64> for Decimal<u128>

Source§

fn from(value: u64) -> Self

Converts to this type from the input type.
Source§

impl From<u8> for Decimal<u128>

Source§

fn from(value: u8) -> Self

Converts to this type from the input type.
Source§

impl<I> FromStr for Decimal<I>

Source§

type Err = ParseError

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

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

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

impl<I: UnderlyingInt, R: Into<Self>> Mul<R> for Decimal<I>

Source§

type Output = Decimal<I>

The resulting type after applying the * operator.
Source§

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

Performs the * operation. Read more
Source§

impl<I: UnderlyingInt, R: Into<Self>> MulAssign<R> for Decimal<I>

Source§

fn mul_assign(&mut self, rhs: R)

Performs the *= operation. Read more
Source§

impl<I: UnderlyingInt> Neg for Decimal<I>

Source§

type Output = Decimal<I>

The resulting type after applying the - operator.
Source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
Source§

impl<I: UnderlyingInt> Ord for Decimal<I>

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<I: UnderlyingInt> PartialEq for Decimal<I>

Source§

fn eq(&self, other: &Self) -> 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<I: UnderlyingInt> PartialOrd for Decimal<I>

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<I: UnderlyingInt> Sub for Decimal<I>

Source§

type Output = Decimal<I>

The resulting type after applying the - operator.
Source§

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

Performs the - operation. Read more
Source§

impl<I: UnderlyingInt> SubAssign for Decimal<I>

Source§

fn sub_assign(&mut self, rhs: Self)

Performs the -= operation. Read more
Source§

impl<'a, I: UnderlyingInt> Sum<&'a Decimal<I>> for Decimal<I>

Source§

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

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

impl<I: UnderlyingInt> Sum for Decimal<I>

Source§

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

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

impl<I: Copy + UnderlyingInt> Copy for Decimal<I>

Source§

impl<I: UnderlyingInt> Eq for Decimal<I>

Auto Trait Implementations§

§

impl<I> Freeze for Decimal<I>
where I: Freeze,

§

impl<I> RefUnwindSafe for Decimal<I>
where I: RefUnwindSafe,

§

impl<I> Send for Decimal<I>
where I: Send,

§

impl<I> Sync for Decimal<I>
where I: Sync,

§

impl<I> Unpin for Decimal<I>
where I: Unpin,

§

impl<I> UnsafeUnpin for Decimal<I>
where I: UnsafeUnpin,

§

impl<I> UnwindSafe for Decimal<I>
where I: UnwindSafe,

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, 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.