1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
pub trait FloatWithPrecision {
    fn round_with_precision(&self, precision: usize) -> Self;
    fn floor_with_precision(&self, precision: usize) -> Self;
    fn ceil_with_precision(&self, precision: usize) -> Self;
}

impl FloatWithPrecision for f64 {
    fn round_with_precision(&self, precision: usize) -> Self {
        let p = 10f64.powi(precision as i32);
        (self * p).round() / p
    }

    fn floor_with_precision(&self, precision: usize) -> Self {
        let p = 10f64.powi(precision as i32);
        (self * p).floor() / p
    }

    fn ceil_with_precision(&self, precision: usize) -> Self {
        let p = 10f64.powi(precision as i32);
        (self * p).ceil() / p
    }
}

impl FloatWithPrecision for f32 {
    fn round_with_precision(&self, precision: usize) -> Self {
        let p = 10f32.powi(precision as i32);
        (self * p).round() / p
    }

    fn floor_with_precision(&self, precision: usize) -> Self {
        let p = 10f32.powi(precision as i32);
        (self * p).floor() / p
    }

    fn ceil_with_precision(&self, precision: usize) -> Self {
        let p = 10f32.powi(precision as i32);
        (self * p).ceil() / p
    }
}