rusty-money
rusty-money handles the messy parts of dealing with money like rounding, precision, parsing and internationalization.
It supports ISO-4217 currencies, common crypto currencies and lets you
define your own. The main items exported by the library are Money
and the iso
and crypto
currency sets.
Usage
A Money
object is created by supplying an amount and a currency. Amounts can be specified in numeric or string types
but will be stored as precise decimals internally. You can select a bundled currency or make your own. Here's a
quick example of how you would make your own Currency
and then create some Money
with it:
use rusty-;
define_currency_set!;
from_major; // 2000 GIL
from_minor; // 2000 GIL
from_str.unwrap; // 2000 GIL
// Currencies can be looked up by code.
let gil = find.unwrap;
from_major; // 2000 GIL
Features: Currency Sets
rusty_money provides two currency sets for convenience : iso
, which implements ISO-4217 currencies and crypto
which
implements popular cryptocurencies. iso
is enabled by default, and you can add crypto
by enabling the feature:
[]
= { = "0.4.0", = ["iso", "crypto"] }
The currency sets can then be used like this:
use rusty-;
from_major; // 2000 U.S Dollars
from_major; // 2000 British Pounds
from_major; // 2 Bitcoin
Money objects of the same currency can be compared:
use rusty-;
let hundred = from_minor;
let thousand = from_minor;
println!; // false
println!; // true
Precision, Rounding and Math
Money objects are immutable, and operations that change amounts create a new instance of Money. Amounts are stored
as 128 bit fixed-precision Decimals, and handle values as large as
296 / 1028. Operations on Money retain the maximum possible precision. When you want less
precision, you call the round
function, which supports three modes:
Money can be added, subtracted, multiplied and divided like this:
use rusty-;
from_minor + from_minor; // 2 USD
from_minor - from_minor; // 0 USD
from_minor * 3; // 3 USD
from_minor / 3; // 0.333... USD
let usd = from_str.unwrap; // 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 rusty-;
let usd = from_str.unwrap;
let eur = from_str.unwrap;
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 rusty-;
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.set_rate;
exchange.get_rate;