rusty-money
A library that handles calculating, rounding, displaying, and parsing units of money according
to ISO 4217 standards. The main items exported by the library are Money
and Currency
.
Usage
Money
consists of an amount, which is represented by a Decimal type that it owns and a
Currency
, which is holds a reference to. Currency
represents an ISO-4217 currency, and
stores metadata like its numeric code, full name and symbol.
// Money can be initialized in a few ways:
use ;
use *;
money!; // 2000 USD
money!; // 2000 USD
new; // 2000 USD
from_major; // 2000 USD
from_minor; // 2000 USD
from_str.unwrap; // 2000 USD
// Money objects with the same Currency can be compared:
let hundred = money!;
let thousand = money!;
println!; // false
println!; // true
Precision and Rounding
Money objects are immutable, and operations that change the amount or currency of Money simply create
a new instance. Money uses a 128 bit fixed-precision Decimal
to represents amounts, and it represents values as large as 296 / 1028. By default
operations on Money always retain maximum possible precision. When you do need to round money, you can call
the round
function, which supports three modes:
use ;
// Money can be added, subtracted, multiplied and divided:
money! + money!; // 200 USD
money! - money!; // 0 USD
money! * 3; // 3 USD
money! / 3; // 0.333333333... USD
// Money can be rounded by calling the round function:
let usd = money!; // 2000.005 USD
usd.round; // 2000.00 USD
usd.round; // 2000.01 USD
usd.round; // 2000 USD
Formatting
Calling format!
or println!
on Money returns a string with a rounded amount, using separators and symbols
according to the locale of the currency. If you need to customize this output, the Formatter
module
accepts a more detailed set of parameters.
use ;
// Money objects can be pretty printed, with appropriate rounding and formatting:
let usd = money!;
let eur = money!;
println!; // -$2,000.01
println!; // -€2.000,01;
Exchange
The library also provides two additional types - Exchange
and ExchangeRates
to convert Money from one currency
to another.
use ;
use *;
use *;
// Convert 1000 USD to EUR at a 2:1 exchange rate.
let rate = new.unwrap;
rate.convert; // 500 EUR
// An Exchange can be used to store ExchangeRates for later use
let mut exchange = new;
exchange.add_or_update_rate;
exchange.get_rate;