Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert u64 to f64

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 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
*/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading