micromath/float/
round.rs

1//! Round a single-precision float.
2
3use super::F32;
4
5impl F32 {
6    /// Returns the nearest integer to a number.
7    pub fn round(self) -> Self {
8        Self(((self.0 + Self(0.5).copysign(self).0) as i32) as f32)
9    }
10}
11
12#[cfg(test)]
13mod tests {
14    use super::F32;
15
16    #[test]
17    fn sanity_check() {
18        assert_eq!(F32(0.0).round(), F32(0.0));
19        assert_eq!(F32(-0.0).round(), F32(-0.0));
20
21        assert_eq!(F32(0.49999).round(), F32(0.0));
22        assert_eq!(F32(-0.49999).round(), F32(-0.0));
23
24        assert_eq!(F32(0.5).round(), F32(1.0));
25        assert_eq!(F32(-0.5).round(), F32(-1.0));
26
27        assert_eq!(F32(9999.499).round(), F32(9999.0));
28        assert_eq!(F32(-9999.499).round(), F32(-9999.0));
29
30        assert_eq!(F32(9999.5).round(), F32(10000.0));
31        assert_eq!(F32(-9999.5).round(), F32(-10000.0));
32    }
33}