Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a number up or down in Rust?

Tags:

rounding

rust

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"
like image 268
GirkovArpa Avatar asked Jun 02 '20 03:06

GirkovArpa


People also ask

How do you round a number in Rust?

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.

Does Ruby round up or down?

Save this question. Show activity on this post.

What number can round down?

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.

Do negative numbers round up or down?

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.


1 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
}
like image 116
Doruk Eren Aktaş Avatar answered Sep 27 '22 22:09

Doruk Eren Aktaş