Module feeless::units [−][src]
Units of Nano, i.e. Rai, Nano (1030), Cents (1022), MicroNano (1024).
Please note these are different from the currently used units, using the proposed new currency units pull request.
Example
use feeless::units::{Nano, Cents}; use std::convert::TryFrom; use std::str::FromStr; // One Nano. let nano = Nano::new(1); // Convert to cents. let cents = nano.to_cents(); assert_eq!(cents, Cents::new(100)); // Works with basic arithmetic. let cents = (cents * Cents::new(-10) + Cents::new(1)) / Cents::new(1000); // Can parse fractional strings. assert_eq!(cents, Cents::from_str("-0.999")?); // Rai is a bounded type that does not allow values outside of u128, so this will fail because // cents is negative. assert!(cents.to_rai().is_err()); let rai = Nano::new(1).to_rai()?; assert_eq!(rai.to_hex_string(), "0000000C9F2C9CD04674EDEA40000000"); assert_eq!(rai.to_u128(), 1_000_000_000_000_000_000_000_000_000_000u128);
Rai differences
Rai acts differently than the other units in this module, as its internal type is u128. This means it can not be a value outside of that, i.e. negative numbers or bigger than u128::MAX. To get around this, use UnboundedRai, which internally uses BigDecimal.
Nano, Cents, MicroNano and UnboundedRai all use BigDecimal internally. These all act in a similar way with conversions between themselves. See the example below.
Example
use feeless::units::Nano; let nano = Nano::new(1).to_cents().to_unbounded_rai().to_micro_nano().to_nano(); assert_eq!(nano, Nano::new(1));
Working with floats (f32, f64)
The general recommendation is to never use floats when dealing with money due to inaccuracies with floating point precision. You can however do it with BigDecimal—see the example below.
Ideally if your API doesn’t support BigDecimal, it might be better to convert between String and BigDecimal to make sure there are no rounding or floating point inaccuracies.
Example
use feeless::units::Cents; use bigdecimal::{BigDecimal, FromPrimitive}; use std::str::FromStr; // If you really need to load from a float, use BigDecimal. let big = BigDecimal::from_f64(1231239999999999.1).unwrap(); let cents = Cents::new(big); // Convert to float. assert_eq!(cents.to_f64(), 1231239999999999.1); // Better let big = BigDecimal::from_str("9999999999.1").unwrap(); let cents = Cents::new(big); assert_eq!(cents.to_string(), "9999999999.1");
Structs
Cents | The Cents (1028 rai) unit denomination. |
MicroNano | The MicroNano (1024 rai) unit denomination. |
Nano | The Nano (1030 rai) unit denomination. |
Rai | Special bounded container for the smallest unit, rai. |
UnboundedRai | The UnboundedRai (100 rai) unit denomination. |