From e9ff5fb30ccb3e8276443df61c274f28ad738cc7 Mon Sep 17 00:00:00 2001 From: Daniel Parks Date: Fri, 15 Mar 2024 21:49:05 -0700 Subject: [PATCH] Make float code work like int code. --- src/lib.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 929c40c..4ab8ee4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -154,23 +154,25 @@ macro_rules! roundable_float { assert!(factor > 0.0, "try_round_to() requires positive factor"); let remainder = self % factor; - let remainder = if remainder < 0.0 { - // Safe: remainder is negative so adding it to factor will - // never overflow (|remainder| < factor). - factor + remainder - } else { - remainder - }; // Safe: remainder has the same sign as self, so subtracting // remainder will always be closer to 0. Also, remainder is // always between 0 and self, so it base can never switch signs. let base = self - remainder; - if remainder < factor / 2.0 { - Some(base) + #[allow(unused_comparisons)] + if self < 0.0 { + if remainder < factor / 2.0 - factor { + Some(base - factor) + } else { + Some(base) + } } else { - Some(base + factor) + if remainder < factor / 2.0 { + Some(base) + } else { + Some(base + factor) + } } } }