From 0e133e4a873757013939b0cbeed9c2a315911b7e Mon Sep 17 00:00:00 2001 From: x3ccd4828 <492528+x3ccd4828@users.noreply.github.com> Date: Sat, 11 Dec 2021 02:17:21 -0500 Subject: [PATCH] fix: format_units return was truncating the decimal places if there were leading zeros (#675) --- ethers-core/src/utils/mod.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ethers-core/src/utils/mod.rs b/ethers-core/src/utils/mod.rs index 722d0e83..64a9c28e 100644 --- a/ethers-core/src/utils/mod.rs +++ b/ethers-core/src/utils/mod.rs @@ -79,7 +79,12 @@ pub fn format_units, K: Into>(amount: T, units: K) -> Strin let amount = amount.into(); let amount_decimals = amount % U256::from(10_u128.pow(units.as_num())); let amount_integer = amount / U256::from(10_u128.pow(units.as_num())); - amount_integer.to_string() + "." + &amount_decimals.to_string() + format!( + "{}.{:0width$}", + amount_integer, + amount_decimals.as_u128(), + width = units.as_num() as usize + ) } /// Converts the input to a U256 and converts from Ether to Wei. @@ -398,6 +403,9 @@ mod tests { let eth = format_units(U256::from_dec_str("1395633240123456789").unwrap(), "ether"); assert_eq!(eth, "1.395633240123456789"); + + let eth = format_units(U256::from_dec_str("1005633240123456789").unwrap(), "ether"); + assert_eq!(eth, "1.005633240123456789"); } #[test]