Introduced from float API for Monero quantities

This commit is contained in:
Franck Royer 2021-02-08 15:24:32 +11:00
parent b5b990257a
commit 60e0b9382c
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
3 changed files with 16 additions and 5 deletions

5
Cargo.lock generated
View File

@ -2885,10 +2885,11 @@ dependencies = [
[[package]] [[package]]
name = "rust_decimal" name = "rust_decimal"
version = "1.9.0" version = "1.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5c739ba050709eae138f053356d27ff818d71fe54ce5a8d9f4c7a660bfb6684" checksum = "e3e5a94e2006dd60c603d8481c65b665b4b6694f78d23e15869ad10eb883e36e"
dependencies = [ dependencies = [
"arrayvec",
"num-traits", "num-traits",
"serde", "serde",
] ]

View File

@ -40,7 +40,7 @@ pem = "0.8"
prettytable-rs = "0.8" prettytable-rs = "0.8"
rand = "0.7" rand = "0.7"
reqwest = { version = "0.11", default-features = false } reqwest = { version = "0.11", default-features = false }
rust_decimal = "1.8" rust_decimal = "1.10"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_cbor = "0.11" serde_cbor = "0.11"
serde_derive = "1.0" serde_derive = "1.0"

View File

@ -15,6 +15,7 @@ use rust_decimal::{
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
convert::TryFrom,
fmt::Display, fmt::Display,
ops::{Add, Mul, Sub}, ops::{Add, Mul, Sub},
str::FromStr, str::FromStr,
@ -88,13 +89,22 @@ impl Amount {
self.0 self.0
} }
pub fn from_monero(amount: f64) -> Result<Self> {
let decimal = Decimal::try_from(amount)?;
Self::from_decimal(decimal)
}
pub fn parse_monero(amount: &str) -> Result<Self> { pub fn parse_monero(amount: &str) -> Result<Self> {
let decimal = Decimal::from_str(amount)?; let decimal = Decimal::from_str(amount)?;
Self::from_decimal(decimal)
}
fn from_decimal(amount: Decimal) -> Result<Self> {
let piconeros_dec = let piconeros_dec =
decimal.mul(Decimal::from_u64(PICONERO_OFFSET).expect("constant to fit into u64")); amount.mul(Decimal::from_u64(PICONERO_OFFSET).expect("constant to fit into u64"));
let piconeros = piconeros_dec let piconeros = piconeros_dec
.to_u64() .to_u64()
.ok_or_else(|| OverflowError(amount.to_owned()))?; .ok_or_else(|| OverflowError(amount.to_string()))?;
Ok(Amount(piconeros)) Ok(Amount(piconeros))
} }
} }