pub trait RoundFloat {
fn round_float(self, decimal: i32) -> Self
where
Self: std::marker::Sized;
}
impl RoundFloat for f64 {
fn round_float(self, decimal: i32) -> f64 {
if decimal <= 0 || self == 0.0 {
self.round()
} else {
let multiplier: f64 = 10.0_f64.powi(decimal);
(self * multiplier).round() / multiplier
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_round_positive_decimal_places() {
let num: f64 = 5.22501;
assert_eq!(num.round_float(2), 5.23);
let num = 12.34567;
assert_eq!(num.round_float(3), 12.346);
let num = 7.89;
assert_eq!(num.round_float(1), 7.9);
let num = 1.2;
assert_eq!(num.round_float(4), 1.2);
let num = -2.789;
assert_eq!(num.round_float(2), -2.79)
}
#[test]
fn test_round_zero_decimal_places() {
let num = 3.6;
assert_eq!(num.round_float(0), 4.0);
let num = 3.4;
assert_eq!(num.round_float(0), 3.0);
}
#[test]
fn test_round_negative_decimal_places() {
let num = 123.456;
assert_eq!(num.round_float(-1), 123.0);
let num = -123.456;
assert_eq!(num.round_float(-2), -123.0);
let num = 123.56;
assert_eq!(num.round_float(-1), 124.0);
}
#[test]
fn test_round_with_zero() {
let num = 0.0;
assert_eq!(num.round_float(2), 0.0);
assert_eq!(num.round_float(0), 0.0);
assert_eq!(num.round_float(-2), 0.0);
}
}