execution_time/traits/
round_float.rs

1/// Trait for rounding floating-point numbers to a specified number of decimal places.
2pub trait RoundFloat {
3    /// Rounds the floating-point number to the given number of decimal places.
4    ///
5    /// ### Arguments
6    ///
7    /// * `decimal` - The number of decimal places to round to.
8    ///
9    /// ### Returns
10    ///
11    /// The rounded floating-point number.
12    fn round_float(self, decimal: i32) -> Self
13    where
14        // This trait is object safe and Sized is required to be object safe
15        Self: std::marker::Sized;
16}
17
18impl RoundFloat for f64 {
19    fn round_float(self, decimal: i32) -> f64 {
20        if decimal <= 0 || self == 0.0 {
21            self.round()
22        } else {
23            let multiplier: f64 = 10.0_f64.powi(decimal);
24            (self * multiplier).round() / multiplier
25        }
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn test_round_positive_decimal_places() {
35        // Test rounding to 2 decimal places
36        let num: f64 = 5.22501;
37        assert_eq!(num.round_float(2), 5.23);
38
39        // Test rounding to 3 decimal places
40        let num = 12.34567;
41        assert_eq!(num.round_float(3), 12.346);
42
43        // Test rounding to 1 decimal place
44        let num = 7.89;
45        assert_eq!(num.round_float(1), 7.9);
46
47        // Test rounding to a greater number of decimal places than available.
48        let num = 1.2;
49        assert_eq!(num.round_float(4), 1.2);
50
51        //Test with a negative number
52        let num = -2.789;
53        assert_eq!(num.round_float(2), -2.79)
54    }
55
56    #[test]
57    fn test_round_zero_decimal_places() {
58        // Test rounding to 0 decimal places (should round to nearest whole number)
59        let num = 3.6;
60        assert_eq!(num.round_float(0), 4.0);
61
62        // Test rounding to 0 decimal places (should round to nearest whole number)
63        let num = 3.4;
64        assert_eq!(num.round_float(0), 3.0);
65    }
66
67    #[test]
68    fn test_round_negative_decimal_places() {
69        // Test rounding with negative decimal places which should be equivalent to round()
70        let num = 123.456;
71        assert_eq!(num.round_float(-1), 123.0);
72
73        // Test rounding with negative decimal places with a negative number
74        let num = -123.456;
75        assert_eq!(num.round_float(-2), -123.0);
76
77        // Test rounding with negative decimal places
78        let num = 123.56;
79        assert_eq!(num.round_float(-1), 124.0);
80    }
81
82    #[test]
83    fn test_round_with_zero() {
84        // Test with zero number, should return 0
85        let num = 0.0;
86        assert_eq!(num.round_float(2), 0.0);
87        assert_eq!(num.round_float(0), 0.0);
88        assert_eq!(num.round_float(-2), 0.0);
89    }
90}