diff --git a/Rust-round-f32-using-arithmetic-and-logical-operators.md b/Rust-round-f32-using-arithmetic-and-logical-operators.md new file mode 100644 index 0000000..2ff3b08 --- /dev/null +++ b/Rust-round-f32-using-arithmetic-and-logical-operators.md @@ -0,0 +1,40 @@ +# round/floor a f32 using logical operations and integer arithmetical operations in Rust + +Yith this function you can able to truncate a float f32 using bitwise, logical operations and integer arithmetical operation. +The function has not 100% of precisition because ignore most of the bits in the mantissa, but it's often to round small numbers. + +```Rust +fn round(mut f: f32) -> i32 { + let sign = f < 0.0; + if sign { + f = f * -1.0; + } + + let digits = f.to_bits(); + + let mut exponent = (digits as i32 >> 23) & (!(1 << 8)); + let mantissa = (digits - (digits >> 23 << 23)) >> 16 | 1 << 7; + + exponent -= 127; + + if exponent < 0 { + return 0; + } + let exponent: u32 = 1 << exponent as u32; + + let mut result: i32 = (exponent * mantissa) as i32 / 128; + if sign { + result *= -1; + } + result +} + +fn main() { + println!("{}", round(15.125)); + println!("{}", round(14.345)); + println!("{}", round(-1.555)); + println!("{}", round(-9.001)); + println!("{}", round(-999.001)); + println!("{}", round(-0.5)); +} +``` \ No newline at end of file