Skip to content

Commit

Permalink
Merge pull request #20 from lavafroth/faster-rounding
Browse files Browse the repository at this point in the history
feat: faster rounding with bitwise and operation
  • Loading branch information
rrwick committed Feb 7, 2024
2 parents 7523fd2 + 225b4da commit f9be6e0
Showing 1 changed file with 4 additions and 11 deletions.
15 changes: 4 additions & 11 deletions src/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,11 @@ pub fn format_duration(duration: std::time::Duration) -> String {
/// round-half-up behaviour. I had tried using math::round::half_to_even, but that didn't seem to
/// work correctly (rounded 42.55 to 42).
pub fn bankers_rounding(float: f64) -> u32 {
let fractional_part = float - float.floor();
let rounded_down = float as u32;
if fractional_part < 0.5 {
return rounded_down;
} else if fractional_part > 0.5 {
return rounded_down + 1;
} else { // fractional_part == 0.5
if rounded_down % 2 == 0 { // is even
return rounded_down;
} else {
return rounded_down + 1;
}
match float.fract() {
f if f < 0.5 => rounded_down,
f if f > 0.5 => rounded_down + 1,
_ => rounded_down + (rounded_down & 1),
}
}

Expand Down

0 comments on commit f9be6e0

Please sign in to comment.