Handle currency conversion and common operations (addition, subtraction, multiplication, division).
It defines some base types:
CurrencyAmount
is i128
and, as the name says, is used to store amounts.CurrencyCode
is a wrapper for [u8; 3]
that can be created from / converted into &str
s.Money
is the most important type. Money holds both a currency_code
and an amount
. It's used
to store money and to perform operations. It can be converted into another currency code by providing
Rates
.Rates
is a wrapper for a HashMap
. It can be constructed from such pre-defined map or ~~populated from
an external source such as websites~~ (Not yet, TODO: Implement).Exponent
exists because there are no float
s involved here. It has two fields: amount
and exponent
. Its decimal value is amount / (10).pow(exponent)
.Even this library isn't safe from precision losses. For example, an Exponent
's amount could be cut out by its exponent. Also errors when converting money could occurr.
Money
s of the same type```rust
use monet::{Money, CurrencyAmount, Rates, Operation}; use std::convert::TryInto;
// Custom rates. let map = vec![("USD", 1000000)].intoiter() .map(|(code, worth)| (code.tryinto().unwrap(), worth.into()) .collect(); let rates = Rates::with_rates(map);
let moneyowned = Money::withstrcode(CurrencyAmount::withunit(2), "USD").unwrap(); let moneypaid = Money::withstrcode(CurrencyAmount::withunit(1), "USD").unwrap();
let remaining = (moneyowned - moneypaid).execute(&rates);
asserteq!(remaining, Money::withstrcode(CurrencyAmount::withunit(1), "USD")); asserteq!(remaining, Money::withstrcode(1000_000.into(), "USD"));
```
Money
s of different type```rust
use monet::{Money, CurrencyAmount, Rates, Operation}; use std::convert::TryInto;
// Custom rates. let map = vec![ ("USD", 1000000), ("CHF", 1100000), ].intoiter() .map(|(code, worth)| (code.tryinto().unwrap(), worth.into()) .collect();
let rates = Rates::with_rates(map);
let moneyone = Money::withstrcode(1000000.into(), "CHF").unwrap(); let moneytwo = Money::withstrcode(1100000.into(), "USD").unwrap();
// Note: sum has currency code "CHF": when summing, // the currency code of the first money is used let sum = (moneyone + moneytwo).execute(&rates);
asserteq!(remaining, Money::withstrcode(2000_000.into(), "CHF"));
```
```rust
use monet::{Money, CurrencyAmount, Rates, Operation}; use std::convert::TryInto;
// Custom rates. let map = vec![ ("USD", 1000000), ("CHF", 1100000), ].intoiter() .map(|(code, worth)| (code.tryinto().unwrap(), worth.into()) .collect();
let rates = Rates::with_rates(map);
let moneyone = Money::withstrcode(1000000.into(), "CHF").unwrap(); let moneytwo = Money::withstrcode(1100000.into(), "USD").unwrap(); let moneythree = Money::withstrcode(2000_000.into(), "CHF").unwrap();
// Note: sum has currency code "CHF" let sum = (moneyone + moneytwo - money_three).execute(&rates);
asserteq!(remaining, Money::withstr_code(0.into(), "CHF"));
```