1 | //! Floating point whole number for a single-precision float. |
2 | |
3 | use super::{F32, MANTISSA_MASK}; |
4 | |
5 | impl F32 { |
6 | /// Returns the integer part of a number. |
7 | pub fn trunc(self) -> Self { |
8 | let x_bits = self.to_bits(); |
9 | let exponent = self.extract_exponent_value(); |
10 | |
11 | // exponent is negative, there is no whole number, just return zero |
12 | if exponent < 0 { |
13 | return F32::ZERO.copysign(self); |
14 | } |
15 | |
16 | let exponent_clamped = i32::max(exponent, 0) as u32; |
17 | |
18 | // find the part of the fraction that would be left over |
19 | let fractional_part = x_bits.overflowing_shl(exponent_clamped).0 & MANTISSA_MASK; |
20 | |
21 | // if there isn't a fraction we can just return the whole thing. |
22 | if fractional_part == 0_u32 { |
23 | return self; |
24 | } |
25 | |
26 | let fractional_mask = fractional_part.overflowing_shr(exponent_clamped).0; |
27 | |
28 | Self::from_bits(x_bits & !fractional_mask) |
29 | } |
30 | } |
31 | |
32 | #[cfg (test)] |
33 | mod tests { |
34 | use super::F32; |
35 | |
36 | #[test ] |
37 | fn sanity_check() { |
38 | assert_eq!(F32(-1.1).trunc(), F32(-1.0)); |
39 | assert_eq!(F32(-0.1).trunc(), F32(-0.0)); |
40 | assert_eq!(F32(0.0).trunc(), F32(0.0)); |
41 | assert_eq!(F32(1.0).trunc(), F32(1.0)); |
42 | assert_eq!(F32(1.1).trunc(), F32(1.0)); |
43 | assert_eq!(F32(2.9).trunc(), F32(2.0)); |
44 | |
45 | assert_eq!(F32(-100_000_000.13425345345).trunc(), F32(-100_000_000.0)); |
46 | assert_eq!(F32(100_000_000.13425345345).trunc(), F32(100_000_000.0)); |
47 | } |
48 | } |
49 | |