round a number to the nearest thousandth in rust

You can use the round() function from the num_traits crate to round a number to a given precision, and the pow() function of the f32 or f64 type to specify the precision as a power of 10. Here is an example code block that rounds a float to the nearest thousandth:

main.rs
use num_traits::Float;

fn round_to_thousandth(x: f32) -> f32 {
    let precision = 3;
    let p = f32::pow(10.0, precision);
    (x * p).round() / p
}

fn main() {
    let x = 1.23456789;
    let y = round_to_thousandth(x as f32);
    println!("{} rounded to the nearest thousandth is {}", x, y);
}
300 chars
14 lines

This will output:

main.rs
1.23456789 rounded to the nearest thousandth is 1.235
54 chars
2 lines

gistlibby LogSnag