How do I convert U256 to different types using alloy primitives?
For example
let num = U256::from(42_u8);
In ethers it's simple, num.to_u128()
but how to do it in alloy?
In alloy you use .to::< >
turbofish to convert between types
let num = U256::from(42_u8);
let a: u128 = num.to::<u128>();
assert_eq!(a, 42);
let b: u64 = num.to::<u64>();
assert_eq!(b, 42);
let c: u32 = num.to::<u32>();
assert_eq!(c, 42);
let d: usize = num.to::<usize>();
assert_eq!(d, 42);
let e: String = num.to_string();
assert_eq!(e, "42");
let f: String = format_units(num, 4)?;
assert_eq!(f, "0.0042");
This is not pretty straight forward from google search, keeping it here for future references.
Source : Github