Skip to main content

embedded_maths/embedded-maths-functions/
round.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! `f32` rounding operations.
3
4/// Returns `x` rounded to the nearest integer.
5///
6/// Values exactly halfway between integers round away from zero.
7#[inline(always)]
8pub fn round(x: f32) -> f32 {
9    if x.is_nan() || x.is_infinite() {
10        return x;
11    }
12    let integer = super::trunc::trunc(x);
13    let fraction = x - integer;
14    let magnitude = if fraction < 0.0 { -fraction } else { fraction };
15    if magnitude >= 0.5 {
16        if fraction > 0.0 {
17            integer + 1.0
18        } else {
19            integer - 1.0
20        }
21    } else {
22        integer
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use super::round;
29
30    #[test]
31    fn nearest_integer() {
32        assert_eq!(round(1.2), 1.0);
33        assert_eq!(round(1.8), 2.0);
34        assert_eq!(round(-1.5), -2.0);
35        assert_eq!(round(-1.4), -1.0);
36    }
37}