round/
lib.rs

1// round - rust library (crate)
2// GNU licensed, license file can be found at the root of the repository
3// Mohamed Hayibor - Copyright 2016
4
5pub fn round(number: f64, rounding: i32) -> f64 {
6  let scale: f64 = 10_f64.powi(rounding);
7  (number * scale).round() / scale
8}
9
10// implementing round_up and round_down with same design pattern
11pub fn round_up(number: f64, rounding: i32) -> f64 {
12  let scale: f64 = 10_f64.powi(rounding);
13  (number * scale).ceil() / scale
14}
15
16pub fn round_down(number: f64, rounding: i32) -> f64 {
17  let scale: f64 = 10_f64.powi(rounding);
18  (number * scale).floor() / scale
19}
20
21#[cfg(test)]
22mod tests {
23  use super::*;
24  
25  #[test]
26  fn test_round() {
27    let pi: f64 = std::f64::consts::PI;
28
29    assert_eq!(round(pi, 0), 3.0);
30    assert_eq!(round(pi, 1), 3.1);
31    assert_eq!(round(pi, 2), 3.14);
32    assert_eq!(round(pi, 3), 3.142);
33    assert_eq!(round(pi, 4), 3.1416);
34    assert_eq!(round(pi, 5), 3.14159);
35    assert_eq!(round(pi, 6), 3.141593);
36    assert_eq!(round(pi, 7), 3.1415927);
37    assert_eq!(round(pi, 8), 3.14159265);
38  }
39
40  #[test]
41  fn test_round_down() {
42    let pi: f64 = std::f64::consts::PI;
43
44    assert_eq!(round_down(pi, 0), 3.0);
45    assert_eq!(round_down(pi, 1), 3.1);
46    assert_eq!(round_down(pi, 2), 3.14);
47    assert_eq!(round_down(pi, 3), 3.141);
48    assert_eq!(round_down(pi, 4), 3.1415);
49    assert_eq!(round_down(pi, 5), 3.14159);
50    assert_eq!(round_down(pi, 6), 3.141592);
51    assert_eq!(round_down(pi, 7), 3.1415926);
52    assert_eq!(round_down(pi, 8), 3.14159265);
53  }
54
55  #[test]
56  fn test_round_up() {
57    let pi: f64 = std::f64::consts::PI;
58    
59    assert_eq!(round_up(pi, 0), 4.0);
60    assert_eq!(round_up(pi, 1), 3.2);
61    assert_eq!(round_up(pi, 2), 3.15);
62    assert_eq!(round_up(pi, 3), 3.142);
63    assert_eq!(round_up(pi, 4), 3.1416);
64    assert_eq!(round_up(pi, 5), 3.14160);
65    assert_eq!(round_up(pi, 6), 3.141593);
66    assert_eq!(round_up(pi, 7), 3.1415927);
67    assert_eq!(round_up(pi, 8), 3.14159266);
68  }
69}