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"
If you want to put the rounded number in a string, use the format!() macro. If you want to round a number and get the result back as another number, then multiply the number by the given power of 10, call round , and divide by the same power, e.g. to round to 2 decimal places, use 102 = 100.
Save this question. Show activity on this post.
If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down. Example: 33 rounded to the nearest ten is 30.
By default, negative numbers with decimal places are rounded away from zero to the nearest integer. For example, -4.7 is rounded down to -5.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With