How to convert a usize to an f64 in Rust

1 Answer

0 votes
/// Converts a `usize` value to its `f64` floating-point representation.
///
/// # Precision & Losslessness
/// On both 32-bit (`usize` max $2^{32}-1$) and 64-bit (`usize` max $2^{64}-1$) architectures,
/// `f64` has a 53-bit mantissa, meaning it can represent integers up to $2^{53} - 1$ ($9,007,199,254,740,991$)
/// with **exact** precision. Values larger than $2^{53}$ on 64-bit platforms will convert smoothly 
/// using IEEE 754 round-to-nearest-even mode.
///
/// # Complexity
/// - Time Complexity: $O(1)$ (Direct CPU instruction).
/// - Memory Complexity: $O(1)$ (Zero-cost abstraction).
#[inline]
pub const fn usize_to_f64(value: usize) -> f64 {
    // Standard primitive numeric cast in Rust
    value as f64
}

fn main() {
    let count: usize = 42;

    // Call wrapper function
    let float_val = usize_to_f64(count);

    // Direct inline conversion idiom
    let direct_val: f64 = count as f64;

    println!("usize: {}, f64: {:.2}", count, float_val);
    println!("Direct cast: {:.2}", direct_val);
}


/*
run:

usize: 42, f64: 42.00
Direct cast: 42.00

*/

 



answered Sep 29 by avibootz
...