Skip to content

Commit

Permalink
Merge pull request #11 from danielparks/float-like-int
Browse files Browse the repository at this point in the history
Make float code work like int code.
  • Loading branch information
danielparks authored Mar 16, 2024
2 parents 2fb7c7a + e9ff5fb commit 522606a
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}
Expand Down

0 comments on commit 522606a

Please sign in to comment.