paupino / rust-decimal

Decimal number implementation written in pure Rust suitable for financial and fixed-precision calculations.
https://docs.rs/rust_decimal/
MIT License
1.03k stars 183 forks source link

Convenience function for one scaled #687

Closed discosultan closed 1 month ago

discosultan commented 1 month ago

Opening this issue simply as a discussion to see if there is any merit in the following. I often find myself creating the following helper function:

use rust_decimal::Decimal;

pub fn precision_to_step(precision: u32) -> Result<Decimal, rust_decimal::Error> {
    let mut one = Decimal::ONE;
    one.set_scale(precision)?;
    Ok(one)
}

#[cfg(test)]
mod tests {
    use rust_decimal_macros::dec;
    use test_case::test_case;

    use super::*;

    #[test_case(0 => Ok(dec!(1)); "0")]
    #[test_case(1 => Ok(dec!(0.1)); "1")]
    #[test_case(5 => Ok(dec!(0.00001)); "5")]
    fn precision_to_step_various(input: u32) -> Result<Decimal, rust_decimal::Error> {
        precision_to_step(input)
    }
}

Wondering if this is a general enough use case that warrants creating a convenience function on the Decimal type such as:

impl Decimal {
    fn one_scaled(scale: u32) -> Result<Self>;
}
Tony-Samuels commented 1 month ago

Decimal::new(1, precision) should do what you want? Or try_new if you can't be confident in the scale.

discosultan commented 1 month ago

@Tony-Samuels Thank you! I missed this part of the API.