Search code examples
rustcastingnumbers

Convert u64 to f64


Given u64 number u64value: u64. How can it be lossy converted into f64? Will u64value as f64 always work?


Solution

  • Since you explicitly stated « lossy », there is no problem. If the original u64 value is quite big, you will lose some lower bits due to the limited precision of the f64.

    See the reference about the type cast expressions with as.

    (see also this answer)

    fn main() {
        let u64value: u64 = 123_456_789_123_456_789;
        let f64value: f64 = u64value as f64;
        let u64back: u64 = f64value as u64;
        println!("u64value: {:?}", u64value);
        println!("f64value: {:?}", f64value);
        println!("u64back: {:?}", u64back);
        println!("delta: {:?}", u64value - u64back);
    }
    /*
    u64value: 123456789123456789
    f64value: 1.2345678912345678e17
    u64back: 123456789123456784
    delta: 5
    */