From 6cecc4824acf48ea7c586ffa64baccfb9a51d0cb Mon Sep 17 00:00:00 2001 From: x3ccd4828 <492528+x3ccd4828@users.noreply.github.com> Date: Fri, 17 Dec 2021 04:22:37 -0500 Subject: [PATCH] fix: parse_units was generating an error on some values because of extra decimal places added round to prevent error (#701) --- ethers-core/src/utils/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ethers-core/src/utils/mod.rs b/ethers-core/src/utils/mod.rs index 690dc492..84fc6f0f 100644 --- a/ethers-core/src/utils/mod.rs +++ b/ethers-core/src/utils/mod.rs @@ -138,11 +138,11 @@ where pub fn parse_units(amount: S, units: K) -> Result where S: ToString, - K: TryInto, + K: TryInto + Copy, { let float_n: f64 = amount.to_string().parse::()? * 10u64.pow(units.try_into()?.as_num()) as f64; - let u256_n: U256 = U256::from_dec_str(&float_n.to_string())?; + let u256_n: U256 = U256::from_dec_str(&float_n.round().to_string())?; Ok(u256_n) } /// The address for an Ethereum contract is deterministically computed from the @@ -430,6 +430,9 @@ mod tests { let gwei = parse_units(1.5, 9).unwrap(); assert_eq!(gwei.as_u64(), 15e8 as u64); + let token = parse_units(1163.56926418, 8).unwrap(); + assert_eq!(token.as_u64(), 116356926418); + let eth_dec_float = parse_units(1.39563324, "ether").unwrap(); assert_eq!(eth_dec_float, U256::from_dec_str("1395633240000000000").unwrap());