From and Into traits and conversion of usize to f64

The problem is that integer → floating point conversions, where the float type is the same size or smaller than the integer, cannot preserve all values. So usizef64 loses precision on 64-bit.

These sorts of conversions are basically the raison d'être for the conv crate, which defines numerous fallible conversions between types (mostly built-in numeric ones). This (as of 10 minutes ago) includes isize/usizef32/f64.

Using conv, you can do this:

use conv::prelude::*;

...

where T: ValueFrom<usize> + ...

...
ans[k] = ans[k - 1] / (k + 1).value_as::<T>().unwrap();
...

Disclaimer: I am the author of the crate in question.


You can do it using as:

let num: f64 = 12 as f64 ;