Skip to main content

Money

Struct Money 

Source
pub struct Money {
    pub currency: Currency,
    pub units: i64,
    pub nanos: Option<i32>,
}
Expand description

Represents an amount of money with its currency type.

Money provides a standardized way to handle monetary values with proper currency identification using ISO 4217 currency codes via the iso_currency::Currency type.

The amount is stored as whole units and nano-fractions to ensure precise decimal representation without floating-point precision issues. Uses i64 for units to enable proper ordering, arithmetic, and comparison operations.

Fields§

§currency: Currency

The currency type using ISO 4217 standard.

Provides access to currency metadata including symbol, decimal places, and full name. Enables type-safe currency operations and proper formatting based on currency conventions.

§units: i64

The whole units of the amount.

The integer portion of the monetary amount. For example, if the amount is $123.45, this field contains 123. The units can be negative for representing debts, refunds, or credit amounts. Note: Google’s API uses strings, but we deserialize to i64 for usability.

§nanos: Option<i32>

Number of nano (10^-9) units of the amount.

The fractional portion expressed in billionths for precise decimal representation. For $123.45, this would be 450,000,000 (0.45 * 10^9). The value must be between -999,999,999 and +999,999,999 inclusive and have the same sign as units.

Implementations§

Source§

impl Money

Source

pub fn currency(&self) -> &Currency

The currency type using ISO 4217 standard.

Provides access to currency metadata including symbol, decimal places, and full name. Enables type-safe currency operations and proper formatting based on currency conventions.

Source§

impl Money

Source

pub fn units(&self) -> i64

The whole units of the amount.

The integer portion of the monetary amount. For example, if the amount is $123.45, this field contains 123. The units can be negative for representing debts, refunds, or credit amounts. Note: Google’s API uses strings, but we deserialize to i64 for usability.

Source

pub fn nanos(&self) -> Option<i32>

Number of nano (10^-9) units of the amount.

The fractional portion expressed in billionths for precise decimal representation. For $123.45, this would be 450,000,000 (0.45 * 10^9). The value must be between -999,999,999 and +999,999,999 inclusive and have the same sign as units.

Source§

impl Money

Source

pub const fn new(currency: Currency, units: i64, nanos: Option<i32>) -> Self

Creates a new Money with the specified currency, units, and nanos.

Used to construct a Money instance with precise control over all components. The nanos value should be between -999,999,999 and +999,999,999 and have the same sign as units for valid monetary representation.

Source

pub fn from_amount( currency_code: &str, amount: f64, ) -> Result<Self, ParseCurrencyError>

Creates Money from a decimal amount and currency code.

Converts a floating-point amount to the precise units + nanos representation. This is convenient for creating Money from user input or calculations, though direct construction is preferred for precision-critical applications.

§Errors

Returns an error if the currency code is not a valid ISO 4217 code.

Source

pub fn zero(currency_code: &str) -> Result<Self, ParseCurrencyError>

Creates Money representing zero amount in the specified currency.

Used for initializing monetary values, representing free items, or as a base for monetary calculations and accumulations.

§Errors

Returns an error if the currency code is not a valid ISO 4217 code.

Source

pub fn currency_code(&self) -> &str

Gets the currency code as a string.

Returns the three-letter ISO 4217 currency code for compatibility with APIs and string-based operations.

Source

pub fn currency_symbol(&self) -> String

Gets the currency symbol for display purposes.

Returns the standard currency symbol (e.g., “$”, “€”, “£”) for user-friendly formatting.

Source

pub fn decimal_places(&self) -> u16

Gets the number of decimal places for this currency.

Returns the standard number of decimal places used by this currency (e.g., 2 for USD/EUR, 0 for JPY, 3 for some Middle Eastern currencies).

Source

pub fn currency_name(&self) -> &str

Gets the currency’s full name for display.

Returns the official currency name (e.g., “United States dollar”, “Euro”, “British Pound”) for detailed displays, tooltips, or educational interfaces.

Source

pub fn to_amount(&self) -> f64

Converts to a decimal amount as f64.

Combines units and nanos into a single floating-point value for display or calculations. Note that this may introduce floating-point precision issues and should be used carefully for financial calculations. If nanos is not specified, treats it as zero.

Source

pub fn is_positive(&self) -> bool

Returns whether this represents a positive amount.

Used for validation, display logic, and business rules that need to distinguish between positive amounts, zero, and negative amounts. If nanos is not specified, only checks units.

Source

pub fn is_zero(&self) -> bool

Returns whether this represents zero amount.

Used to identify free items, no-cost services, or zeroed balances in financial calculations and display logic. If nanos is not specified, treats it as zero.

Source

pub fn is_negative(&self) -> bool

Returns whether this represents a negative amount.

Used to identify debts, refunds, credits, or discounts in financial applications and business logic. If nanos is not specified, only checks units.

Source

pub fn format(&self) -> String

Formats the money amount for display.

Creates a user-friendly representation of the monetary amount with appropriate currency symbol and decimal formatting based on the currency’s standard conventions.

Source

pub fn format_amount_only(&self) -> String

Formats the money amount without currency symbol.

Provides numerical formatting with appropriate decimal places but without currency symbol, useful for tables, calculations display, or when currency is indicated elsewhere.

Source

pub fn format_with_code(&self) -> String

Formats with explicit currency code.

Creates a display format that includes the ISO currency code, useful for international applications or when currency symbols might be ambiguous (e.g., “123.45 USD”).

Source

pub fn is_valid(&self) -> bool

Returns whether this money is valid for financial operations.

Validates that the nanos value, if present, is within the valid range for proper monetary representation. Currency is guaranteed to be valid since it’s typed as Currency. Returns true if nanos is not specified.

Source

pub fn is_major_currency(&self) -> bool

Returns whether this currency is a major trading currency.

Used to identify widely-used international currencies for special handling in currency conversion, trading applications, or financial analysis.

Source

pub fn is_cryptocurrency(&self) -> bool

Returns whether this is a cryptocurrency.

Identifies digital currencies for specialized handling, though most cryptocurrencies may not be in the ISO 4217 standard and would need custom handling beyond this basic check.

Source

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

Compares amounts assuming same currency.

Provides ordering comparison for sorting and filtering operations. Only compares amounts, not currency types - use with caution for mixed-currency collections. Treats missing nanos as zero for comparison purposes.

Source

pub fn compact_format(&self) -> String

Returns a compact representation for space-constrained displays.

Provides abbreviated formatting suitable for mobile interfaces, tables, or dashboard displays where space is limited.

Trait Implementations§

Source§

impl Clone for Money

Source§

fn clone(&self) -> Money

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 Money

Source§

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

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

impl<'de> Deserialize<'de> for Money

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

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

impl Display for Money

Source§

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

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

impl From<&Money> for Currency

Source§

fn from(money: &Money) -> Self

Converts Money reference to its Currency type.

Convenience implementation for extracting currency information without taking ownership.

Source§

impl From<Money> for Currency

Source§

fn from(money: Money) -> Self

Converts Money to its Currency type.

Enables extraction of currency metadata from Money instances for currency-specific operations.

Source§

impl Hash for Money

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 Money

Source§

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

Provides total ordering for money amounts.

Orders money values by their amounts (units and nanos) for sorting operations. Does not consider currency in the comparison - use with caution when working with mixed-currency collections. Missing nanos values are treated as zero.

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 Money

Source§

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

Source§

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

Compares money amounts for ordering.

Compares only the monetary amounts (units and nanos), not currency types. This enables sorting and filtering operations on money values. Missing nanos values are treated as zero for comparison purposes.

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 Serialize for Money

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

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

impl Eq for Money

Source§

impl StructuralPartialEq for Money

Auto Trait Implementations§

§

impl Freeze for Money

§

impl RefUnwindSafe for Money

§

impl Send for Money

§

impl Sync for Money

§

impl Unpin for Money

§

impl UnwindSafe for Money

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

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

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

Compare self to key and return true if they are equal.
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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> ToStringFallible for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

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.
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
Source§

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

Source§

impl<T> ErasedDestructor for T
where T: 'static,