You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm trying to create a library that rounds float types (f32 and f64) to a specified number of digits by calling on the "round()" function along with some other operations. Right now it's pretty inconvenient to make such an implementation. I tried using type_name but it gets kinda messy:
#![allow(clippy::let_and_return)]
pub mod round_float {
use std::any::type_name;
use anyhow::Result;
use cast::f64;
pub fn round_float<T>(full_float: T, digits: u32) -> Result<f64> {
let type_name = type_name_of(full_float);
if type_name == "f32" || type_name == "f64" {
return Err(anyhow::Error::msg("Expected `f32` or `f64`."));
}
let float64 = f64::from(full_float);
let round_factor = 10.0 * f64(digits);
let rounded_float = (full_float * round_factor).round() / round_factor;
rounded_float
}
fn type_name_of<T>(_: T) -> &'static str {
type_name::<T>()
}
}
I also tried using the approach where I create a new trait called Float and implement it on f32 and f64 and then pass a generic argument into round_float() that has the Float trait. The problem is that this empty Float trait doesn't have the round() method that's shared by f32 and f64.
The above example demonstrates the need to refactor the methods shared between f32 and f64 into a trait in the standard library so that anyone who wishes to do something specific to float numbers (both f32 and f64) can do so more conveniently by using the Float trait in the generic argument and thereby accessing the methods shared in common between f32 and f64.
The text was updated successfully, but these errors were encountered:
I'm trying to create a library that rounds float types (f32 and f64) to a specified number of digits by calling on the "round()" function along with some other operations. Right now it's pretty inconvenient to make such an implementation. I tried using
type_name
but it gets kinda messy:I also tried using the approach where I create a new trait called
Float
and implement it onf32
andf64
and then pass a generic argument intoround_float()
that has theFloat
trait. The problem is that this emptyFloat
trait doesn't have theround()
method that's shared byf32
andf64
.The above example demonstrates the need to refactor the methods shared between
f32
andf64
into a trait in the standard library so that anyone who wishes to do something specific to float numbers (bothf32
andf64
) can do so more conveniently by using theFloat
trait in the generic argument and thereby accessing the methods shared in common betweenf32
andf64
.The text was updated successfully, but these errors were encountered: