Skip to content

Instantly share code, notes, and snippets.

@juliarose
Created February 27, 2023 03:39
Show Gist options
  • Save juliarose/71c315eb2d11921f0c26d17af9692328 to your computer and use it in GitHub Desktop.
Save juliarose/71c315eb2d11921f0c26d17af9692328 to your computer and use it in GitHub Desktop.
Rounds number to the nearest divisor.
use num_traits::cast::AsPrimitive;
/// Rounds number to the nearest divisor.
pub fn round_to_nearest_divisor<T>(num: T, divisor: T) -> T
where
T: AsPrimitive<f32>,
f32: AsPrimitive<T>,
{
let divisor: f32 = divisor.as_();
let num: f32 = num.as_();
((num / divisor).round() * divisor).as_()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rounds_correctly() {
assert_eq!(round_to_nearest_divisor(4, 5), 5);
assert_eq!(round_to_nearest_divisor(-1, 5), 0);
assert_eq!(round_to_nearest_divisor(-4, 5), -5);
assert_eq!(round_to_nearest_divisor(66, 20), 60);
assert_eq!(round_to_nearest_divisor(104, 100), 100);
assert_eq!(round_to_nearest_divisor(104 as usize, 100), 100);
assert_eq!(round_to_nearest_divisor(8.0, 10.0), 10.0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment