fix: format_units return was truncating the decimal places if there were leading zeros (#675)

This commit is contained in:
x3ccd4828 2021-12-11 02:17:21 -05:00 committed by GitHub
parent 38e18463dc
commit 0e133e4a87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 1 deletions

View File

@ -79,7 +79,12 @@ pub fn format_units<T: Into<U256>, K: Into<Units>>(amount: T, units: K) -> Strin
let amount = amount.into(); let amount = amount.into();
let amount_decimals = amount % U256::from(10_u128.pow(units.as_num())); let amount_decimals = amount % U256::from(10_u128.pow(units.as_num()));
let amount_integer = 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. /// 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"); let eth = format_units(U256::from_dec_str("1395633240123456789").unwrap(), "ether");
assert_eq!(eth, "1.395633240123456789"); assert_eq!(eth, "1.395633240123456789");
let eth = format_units(U256::from_dec_str("1005633240123456789").unwrap(), "ether");
assert_eq!(eth, "1.005633240123456789");
} }
#[test] #[test]