How can I safely convert a floating point type (e.g. f64) to and integer type (e.g. u64)? In other words I want to convert the number but only if it actually can be represented by the target type.
I found a couple of questions that don't cover this and are not duplicates:
The solution is not to use as - that performs a saturating cast. Also u64::try_from(f64) is not implemented.
The closest seems to be f64::to_int_unchecked() but unfortunately it's unsafe. You can easily check the first two safety requirements (not NaN or infinity), but the third is a bit tedious: Be representable in the return type Int, after truncating off its fractional part.
The best I can come up with is to use as to convert it back to f64 and check equality, i.e.
fn convert(x: f64) -> Option<u64> {
let y = x as u64;
if y as f64 == x {
Some(y)
} else {
None
}
}
Is that the best option? Is it implemented anywhere?