How to round a number up or down in Rust?

Viewed 20231

How to floor or ceil numbers? I tried to use the round crate but either it doesn't work or I'm using it wrong.

use round::round_down;

fn main() {
  println!("{}", round_down(5.5f64, 0));  
}

This prints 5.5 but should print 5.

My Cargo.toml file contains this:

[dependencies]
round = "0.1.0"
2 Answers

As stated in the comments you can use: floor and ceil

fn main() {
    let num_32 = 3.14159_f32;

    println!("{}", num_32.floor()); // Output: 3
    println!("{}", num_32.ceil()); // Output: 4


    let num_64 = 3.14159_f64;

    println!("{}", num_64.floor()); // Output: 3
    println!("{}", num_64.ceil()); // Output: 4
}
fn main() {
  let mut num = 5.5_f64;
  num = num.floor();
  print!("{}", num); // 5
}
Related