fix: support formatting large units (#1608)
This commit is contained in:
parent
2083841200
commit
3681099af3
|
@ -41,7 +41,7 @@ cargo_metadata = { version = "0.15.0", optional = true }
|
||||||
convert_case = { version = "0.5.0", optional = true }
|
convert_case = { version = "0.5.0", optional = true }
|
||||||
syn = { version = "1.0.99", optional = true }
|
syn = { version = "1.0.99", optional = true }
|
||||||
proc-macro2 = { version = "1.0.43", optional = true }
|
proc-macro2 = { version = "1.0.43", optional = true }
|
||||||
rust_decimal = "1.26.1"
|
rust_decimal = { version = "1.26.1", features = ["maths"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
serde_json = { version = "1.0.64", default-features = false }
|
serde_json = { version = "1.0.64", default-features = false }
|
||||||
|
|
|
@ -155,9 +155,15 @@ where
|
||||||
S: ToString,
|
S: ToString,
|
||||||
K: TryInto<Units, Error = ConversionError> + Copy,
|
K: TryInto<Units, Error = ConversionError> + Copy,
|
||||||
{
|
{
|
||||||
use rust_decimal::Decimal;
|
use rust_decimal::{Decimal, MathematicalOps};
|
||||||
|
|
||||||
let num: Decimal = amount.to_string().parse()?;
|
let num: Decimal = amount.to_string().parse()?;
|
||||||
let multiplier: Decimal = 10u64.pow(units.try_into()?.as_num()).into();
|
let exponent = units.try_into()?.as_num();
|
||||||
|
|
||||||
|
let multiplier = Decimal::TEN
|
||||||
|
.checked_powu(exponent.into())
|
||||||
|
.ok_or(rust_decimal::Error::ExceedsMaximumPossibleValue)?;
|
||||||
|
|
||||||
let val =
|
let val =
|
||||||
num.checked_mul(multiplier).ok_or(rust_decimal::Error::ExceedsMaximumPossibleValue)?;
|
num.checked_mul(multiplier).ok_or(rust_decimal::Error::ExceedsMaximumPossibleValue)?;
|
||||||
let u256_n: U256 = U256::from_dec_str(&val.round().to_string())?;
|
let u256_n: U256 = U256::from_dec_str(&val.round().to_string())?;
|
||||||
|
@ -441,6 +447,14 @@ mod tests {
|
||||||
assert_eq!(eth, "1.005633240123456789");
|
assert_eq!(eth, "1.005633240123456789");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_large_units() {
|
||||||
|
let decimals = 27u32;
|
||||||
|
let val = "10.55";
|
||||||
|
let unit = parse_units(val, decimals).unwrap();
|
||||||
|
assert_eq!(unit.to_string(), "10550000000000000000000000000");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_units() {
|
fn test_parse_units() {
|
||||||
let gwei = parse_units(1.5, 9).unwrap();
|
let gwei = parse_units(1.5, 9).unwrap();
|
||||||
|
|
Loading…
Reference in New Issue