embedded_maths/embedded-maths-functions/
round.rs1#[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}