Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion to make this a trait #5

Open
akberg opened this issue Mar 2, 2023 · 0 comments
Open

Suggestion to make this a trait #5

akberg opened this issue Mar 2, 2023 · 0 comments

Comments

@akberg
Copy link

akberg commented Mar 2, 2023

Hi!
I found this crate for the same reason you created it – I find myself using decimal rounding so often it bugs me that there is no built-in support for it, so I would check if a crate for it existed before going on and creating one myself. But, for this API to flow better with the Rust APIs, I do have some suggestions:

  • Use f64::powi/f32::powi to remove the limitation set by hard-coding each order of magnitude (saw that this is exactly what more freedom to round #1 suggested 3 years ago, so I'll consider this crate dead): Sorry, this was already added, I was looking at an outdated commit.
fn round(n: f32, i: u32) -> f32 {
  (n * 10u32.pow(i) as f32).round() / 10u32.pow(i) as f32
}
  • The std already has a function called round (f32::round() -> u32), consider renaming it to e.g. roundf to emphasize that the return value is a float.
  • Consider making it a trait instead (or in addition):
trait RoundF {
    fn roundf(&self, rounding: i32) -> Self;
    fn ceilf(&self, rounding: i32) -> Self;
    fn floorf(&self, rounding: i32) -> Self;
}
impl RoundF for f32 {
    fn roundf(&self, rounding: i32) -> f32 {
        (self * 10.0f32.powi(rounding)).round() / 10.0f32.powi(rounding)
    }
    . . .
}
impl RoundF for f64 {
    fn roundf(&self, rounding: i32) -> f64 {
        (self * 10.0f64.powi(rounding)).round() / 10.0f64.powi(rounding)
    }
    . . .
}
@akberg akberg changed the title Use powi to remove limitation, and suggestion to make this a trait Suggestion to make this a trait Mar 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant