Skip to main content

paycheck_utils/
utils.rs

1//! Utility functions for paycheck calculations and formatting.
2//!This module includes functions for rounding values to 2 decimal places and formatting output for display.
3
4/// Rounds a f32 value to 2 decimal places
5/// # Arguments
6/// * `value` - f32 value to be rounded
7/// # Returns
8/// * `f32` - rounded value to 2 decimal places
9/// # Example
10/// ```
11/// use paycheck_utils::utils::round_2_decimals;
12///
13/// let rounded_value = round_2_decimals(123.4567);
14/// assert_eq!(rounded_value, 123.46);
15/// ```
16/// # Notes
17/// * Uses standard rounding rules
18///
19pub fn round_2_decimals(value: f32) -> f32 {
20    (value * 100.0).round() / 100.0
21}
22
23use std::any::{Any, TypeId};
24use std::str::FromStr;
25
26pub fn check_converted_value<T: Any + FromStr>(
27    result: &Result<T, T::Err>,
28    expected_type: TypeId,
29) -> bool {
30    match result {
31        Ok(value) => value.type_id() == expected_type,
32        Err(_) => false,
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn test_round_2_decimals() {
42        assert_eq!(round_2_decimals(123.4567), 123.46);
43        assert_eq!(round_2_decimals(123.451), 123.45);
44        assert_eq!(round_2_decimals(123.455), 123.46);
45        assert_eq!(round_2_decimals(123.454), 123.45);
46    }
47
48    #[test]
49    fn test_check_converted_value() {
50        let result_ok: Result<f32, _> = "123.45".parse::<f32>();
51        let result_err: Result<f32, _> = "abc".parse::<f32>();
52        assert!(check_converted_value(&result_ok, TypeId::of::<f32>()));
53        assert!(!check_converted_value(&result_err, TypeId::of::<f32>()));
54    }
55}