headless_lms_utils/
numbers.rs1pub fn f32_approx_eq(first: f32, second: f32) -> bool {
2 let diff = first - second;
3 diff.abs() < 0.000001
4}
5
6pub fn f32_max(first: f32, second: f32) -> f32 {
7 if first > second { first } else { second }
8}
9
10pub fn option_f32_to_f32_two_decimals_with_none_as_zero(value: Option<f32>) -> f32 {
11 match value {
12 Some(float) => f32_to_two_decimals(float),
13 None => 0.0,
14 }
15}
16pub fn f32_to_two_decimals(value: f32) -> f32 {
17 (value * (100_f32)).round() / (100_f32)
18}
19
20pub fn f32_to_three_decimals(value: f32) -> f32 {
21 (value * (1000_f32)).round() / (1000_f32)
22}
23
24#[cfg(test)]
25mod tests {
26 use super::*;
27
28 #[test]
29 fn f32_approx_eq_works() {
30 assert!(!f32_approx_eq(1.0, 1.1));
31 assert!(!f32_approx_eq(-1.1, 1.1));
32 assert!(!f32_approx_eq(1.1, -1.1));
33 assert!(f32_approx_eq(1.1, 1.1));
34 assert!(f32_approx_eq(0.0, 0.0));
35 }
36
37 #[test]
38 fn f32_to_two_decimals_works() {
39 assert_eq!(f32_to_two_decimals(1.0), 1.0);
40 assert_eq!(f32_to_two_decimals(1.1), 1.1);
41 assert_eq!(f32_to_two_decimals(1.111_111), 1.11);
42 assert_eq!(f32_to_two_decimals(1.355555), 1.36);
43 assert_eq!(f32_to_two_decimals(1.000000001), 1.0);
44 }
45
46 #[test]
47 fn f32_to_three_decimals_works() {
48 assert_eq!(f32_to_three_decimals(1.0), 1.0);
49 assert_eq!(f32_to_three_decimals(1.1), 1.1);
50 assert_eq!(f32_to_three_decimals(1.111_111), 1.111);
51 assert_eq!(f32_to_three_decimals(1.355555), 1.356);
52 assert_eq!(f32_to_three_decimals(1.000000001), 1.0);
53 }
54}