finance_solution/
round.rs1pub fn round_2(val: f64) -> f64 {
6 (val * 100.0).round() / 100.0
7}
8
9pub fn round_4(val: f64) -> f64 {
12 (val * 10_000.0).round() / 10_000.0
13}
14
15pub fn round_6(val: f64) -> f64 {
18 (val * 1_000_000.0).round() / 1_000_000.0
19}
20
21pub fn round_8(val: f64) -> f64 {
24 (val * 100_000_000.0).round() / 100_000_000.0
25}
26
27#[inline(always)]
28pub fn assert_rounded_2(val_1: f64, val_2: f64) {
29 assert!(val_1.is_finite());
30 assert!(val_2.is_finite());
31 assert_eq!(round_2(val_1), round_2(val_2));
32}
33
34#[inline(always)]
35pub fn assert_rounded_4(val_1: f64, val_2: f64) {
36 assert!(val_1.is_finite());
37 assert!(val_2.is_finite());
38 assert_eq!(round_4(val_1), round_4(val_2));
39}
40
41#[inline(always)]
42pub fn assert_rounded_6(val_1: f64, val_2: f64) {
43 assert!(val_1.is_finite());
44 assert!(val_2.is_finite());
45 assert_eq!(round_6(val_1), round_6(val_2));
46}
47
48#[inline(always)]
49pub fn assert_rounded_8(val_1: f64, val_2: f64) {
50 assert!(val_1.is_finite());
51 assert!(val_2.is_finite());
52 assert_eq!(round_8(val_1), round_8(val_2));
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use crate::*;
59
60 #[test]
61 fn test_equals_zero() {
62 assert_eq!(0.0f64, 0.0f64);
63 assert_eq!(-0.0f64, -0.0f64);
64 assert_eq!(0.0f64, -0.0f64);
65 }
66
67 #[test]
68 fn test_round_2() {
69 assert_eq!(295_489.94, round_2(295_489.941849));
70 assert_eq!(295_489.94, round_2(295_489.9449));
71 assert_ne!(295_489.94, round_2(295_489.9451234));
72 }
73
74 #[test]
75 fn test_round_4() {
76 assert_eq!(295_489.9418, round_4(295_489.941849));
77 assert_eq!(295_489.9418, round_4(295_489.94175));
78 assert_ne!(295_489.9418, round_4(295_489.94185));
79 }
80
81 #[test]
82 fn test_round_6() {
83 assert_eq!(295_489.941849, round_6(295_489.9418494449));
84 assert_eq!(295_489.533367, round_6(295_489.5333669999999));
85 assert_eq!(295_489.945123, round_6(295_489.9451229999));
86 assert_ne!(295_489.945123, round_6(295_489.9451249999));
87 }
88
89 #[test]
90 fn test_round_8() {
91 assert_eq!(295_489.94184944, round_8(295_489.9418494449));
92 assert_eq!(295_489.53336700, round_8(295_489.5333669999999));
93 assert_eq!(295_489.94512333, round_8(295_489.945123329999));
94 assert_ne!(295_489.94512333, round_8(295_489.9451249999));
95 }
96
97 #[test]
98 fn test_assert_rounded_2_nominal() {
99 assert_rounded_2!(53_243.7448, 53_243.7401);
100 }
101
102 #[test]
103 #[should_panic]
104 fn test_assert_rounded_2_panic() {
105 assert_rounded_2!(53_243.7458, 53_243.7401);
106 }
107
108 #[test]
116 #[should_panic]
117 fn test_assert_approx_equal_panic() {
118 assert_rounded_2!(53_243.8123, 53_243.7401);
119 }
120
121}
122
123