How can I fallibly convert a float to an integer?

I can't figure out how to get a float into an unsigned integer. There doesn't seem to be anything like TryFrom for this conversion and simply coercing to the target type produces produces invalid results. e. g.

let f = -1234.456f64;
f.trunc() as u64 // produces `0` when what I need in this case is an Err

You can use the num_traits::cast function, or the related traits:

let f = -1234.456f64;
let d: Option<u64> = num_traits::cast(f);
assert_eq!(d, None);


1 Like

Perfect, thanks

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.