25

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
  • 4,427
  • 4
  • 14
  • 43
  • Does this answer your question? [How does one round a floating point number to a specified number of digits?](https://stackoverflow.com/questions/28655362/how-does-one-round-a-floating-point-number-to-a-specified-number-of-digits) – Doruk Eren Aktaş Jun 02 '20 at 04:00
  • The package doesn't claim to handle rounding to zero digits (it says 1 to 10). Why not [use `math::round::floor`](https://docs.rs/libmath/0.1.4/math/round/fn.floor.html)? – ShadowRanger Jun 02 '20 at 04:02
  • @dorukerenaktas: That handles regular rounding, not floor rounding, right? – ShadowRanger Jun 02 '20 at 04:03
  • 1
    follow documentation of Primitive Type f64: https://doc.rust-lang.org/std/primitive.f64.html – Alcastic Jun 02 '20 at 04:05

3 Answers3

38

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
}
Doruk Eren Aktaş
  • 2,121
  • 8
  • 23
3
fn main() {
  let mut num = 5.5_f64;
  num = num.floor();
  print!("{}", num); // 5
}
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
3

if you have only integers, you may use this trick:

// down
a / b

// up
a / b + (a % b).signum()

Example:

let a: i32 = 5;
let b: i32 = 2;

// down
println!("floor = {}" , a / b);

// up
println!("ceil = {}" , a / b + (a % b).signum());

playground

German Khokhlov
  • 1,724
  • 16
  • 15