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
}
Related videos on Youtube
Author by
GirkovArpa
Updated on September 15, 2022Comments
-
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 print5
.My
Cargo.toml
file contains this:[dependencies] round = "0.1.0"
-
Alcastic almost 4 yearsfollow documentation of Primitive Type f64: doc.rust-lang.org/std/primitive.f64.html
-
-
GirkovArpa almost 4 yearsEven with the
math = "0.1.0"
dependency I getunresolved import 'math::round'
:no 'round' in the root
. -
Doruk Eren Aktaş almost 4 yearsDependency name is libmath, and version is 0.2.1.
-
IInspectable almost 4 years
-
Doruk Eren Aktaş almost 4 years@IInspectable the provided functions are for
f32
, in the questionf64
is asked as i understand correctly. -
Jussi Kukkonen almost 4 yearsThe exact same functions are of course available for f64
-
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 over 2 years
i32
doesn't have afloor()
method because you can't round an integer.