How to round a number up or down in Rust?

11,670

Solution 1

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
}

Solution 2

fn main() {
  let mut num = 5.5_f64;
  num = num.floor();
  print!("{}", num); // 5
}
Share:
11,670

Related videos on Youtube

GirkovArpa
Author by

GirkovArpa

Updated on September 15, 2022

Comments

  • GirkovArpa
    GirkovArpa over 1 year

    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"
    
  • GirkovArpa
    GirkovArpa almost 4 years
    Even with the math = "0.1.0" dependency I get unresolved import 'math::round': no 'round' in the root.
  • Doruk Eren Aktaş
    Doruk Eren Aktaş almost 4 years
    Dependency name is libmath, and version is 0.2.1.
  • IInspectable
    IInspectable almost 4 years
    I don't understand, why this crate exists. floor and ceil are provided by the language already.
  • Doruk Eren Aktaş
    Doruk Eren Aktaş almost 4 years
    @IInspectable the provided functions are for f32, in the question f64 is asked as i understand correctly.
  • Jussi Kukkonen
    Jussi Kukkonen almost 4 years
    The exact same functions are of course available for f64
  • Doruk Eren Aktaş
    Doruk Eren Aktaş almost 4 years
    @JussiKukkonen you are right. I checked it now. It's my fault that i did not searched it correctly in the docs.
  • GirkovArpa
    GirkovArpa over 2 years
    i32 doesn't have a floor() method because you can't round an integer.