#financial #fixed #precision #currency

commodity

A library for representing commodities/currencies, and exchange rates/conversions between them

14 unstable releases (3 breaking)

0.4.0 Jun 17, 2020
0.3.7 Jun 17, 2020
0.3.5 May 10, 2020
0.3.4 Apr 28, 2020
0.1.1 Mar 2, 2020

#313 in Math

Download history 33/week @ 2022-03-10 73/week @ 2022-03-17 4/week @ 2022-03-24 5/week @ 2022-03-31 6/week @ 2022-04-07 6/week @ 2022-04-14 6/week @ 2022-04-21 74/week @ 2022-04-28 88/week @ 2022-05-05 231/week @ 2022-05-12 65/week @ 2022-05-19 79/week @ 2022-05-26 132/week @ 2022-06-02 4/week @ 2022-06-09 10/week @ 2022-06-16 24/week @ 2022-06-23

185 downloads per month
Used in doublecount

MIT license

46KB
662 lines

Commodity crates.io badge docs.rs badge license badge github action badge

A library for representing commodities/currencies, and exchange rates/conversions between them in Rust. Values are backed by the rust_decimal library.

Changelog

Optional Features

The following features can be enabled to provide extra functionality:

  • serde-support
    • Enables support for serialization/de-serialization via serde

Example

use commodity::{Commodity, CommodityType, CommodityTypeID};
use rust_decimal::Decimal;
use std::str::FromStr;

// Create a commodity type from a currency's iso4317 three character code.
// The CommodityType stores information associated with that currency,
// such as the full name ("United States dollar" for this one).
let usd = CommodityType::from_currency_alpha3("USD").unwrap();

// Create a commodity with a value of "2.02 USD"
let commodity1 = Commodity::new(Decimal::from_str("2.02").unwrap(), &usd);

// Create commodities using the `from_str` method
let commodity2 = Commodity::from_str("24.00 USD").unwrap();

// Create commodity using a CommodityTypeID
let nzd_code = CommodityTypeID::from_str("NZD").unwrap();
let commodity3 = Commodity::new(Decimal::from_str("24.00").unwrap(), nzd_code);

// Add two compatible (same currency) commodities, the result has
// the same currency (in this case, "USD").
let commodity4 = commodity1.add(&commodity2).unwrap();

// Try to subtract two incompatible commodities
let result = commodity3.sub(&commodity2);
assert!(result.is_err());

Dependencies

~1.3–2MB
~38K SLoC