round a number to the nearest tenth in rust

To round a number to the nearest tenth in Rust, you can make use of the built-in floating-point math functions. Here's an example function that rounds a given floating point number to the nearest tenth:

main.rs
fn round_to_tenth(num: f64) -> f64 {
    (num * 10.0).round() / 10.0
}
71 chars
4 lines

This function multiplies the input number by 10, rounds the result to the nearest integer using the round() function, and then divides the result by 10 to obtain a number rounded to the nearest tenth.

Here's an example usage of the function:

main.rs
fn main() {
    let num = 3.14159;
    let rounded = round_to_tenth(num);
    println!("{} rounded to the nearest tenth is {}", num, rounded);
}
145 chars
6 lines

This would produce the output:

3.14159 rounded to the nearest tenth is 3.1
44 chars
2 lines

gistlibby LogSnag