Skip to main content

scratch_test_value/math/
round.rs

1use crate::SNumber;
2
3impl SNumber {
4    pub fn floor(&self) -> SNumber {
5        match self {
6            Self::Int(i) => Self::Int(*i),
7            Self::Float(f) => {
8                if f.is_nan() {
9                    return Self::Int(0);
10                }
11                let f = f.floor();
12                if f.abs() < (i64::MAX as f64) {
13                    Self::Int(f as i64)
14                } else {
15                    Self::Float(f)
16                }
17            }
18        }
19    }
20    pub fn ceil(&self) -> SNumber {
21        match self {
22            Self::Int(i) => Self::Int(*i),
23            Self::Float(f) => {
24                if f.is_nan() {
25                    return Self::Int(0);
26                }
27                let f = f.ceil();
28                if f.abs() < (i64::MAX as f64) {
29                    Self::Int(f as i64)
30                } else {
31                    Self::Float(f)
32                }
33            }
34        }
35    }
36    pub fn round(&self) -> SNumber {
37        match self {
38            Self::Int(i) => Self::Int(*i),
39            Self::Float(f) => {
40                if f.is_nan() {
41                    return Self::Int(0);
42                }
43                let f = f.round();
44                if f.abs() < (i64::MAX as f64) {
45                    Self::Int(f as i64)
46                } else {
47                    Self::Float(f)
48                }
49            }
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use crate::SNumber;
57
58    #[test]
59    fn test_round_negative() {
60        assert_eq!(SNumber::Int(-2), SNumber::Float(-2.4).round());
61    }
62
63    #[test]
64    fn test_round_special() {
65        for s in [SNumber::INFINITY, SNumber::NEG_INFINITY] {
66            assert_eq!(s, s.round());
67            assert_eq!(s, s.ceil());
68            assert_eq!(s, s.floor());
69        }
70        assert_eq!(SNumber::Int(0), SNumber::NAN.round());
71        assert_eq!(SNumber::Int(0), SNumber::NAN.ceil());
72        assert_eq!(SNumber::Int(0), SNumber::NAN.floor());
73    }
74}