diff --git a/src/decimal.rs b/src/decimal.rs index e8f49225..af20c6c8 100644 --- a/src/decimal.rs +++ b/src/decimal.rs @@ -805,6 +805,21 @@ impl Decimal { } } + /// Returns a new `Decimal` with the fractional portion delimited by `scale`. + /// + /// # Example + /// + /// ``` + /// # use rust_decimal::Decimal; + /// # + /// let trunc = Decimal::from_parts(31415, 0, 0, false, 4); + /// assert_eq!(Decimal::PI.trunc_with_scale(4), trunc); + /// ``` + #[must_use] + pub fn trunc_with_scale(&self, scale: u32) -> Decimal { + self.round_dp_with_strategy(scale, RoundingStrategy::ToZero) + } + /// Returns a new `Decimal` representing the fractional portion of the number. /// /// # Example diff --git a/tests/decimal_tests.rs b/tests/decimal_tests.rs index 7bdf07dc..0ff5a65b 100644 --- a/tests/decimal_tests.rs +++ b/tests/decimal_tests.rs @@ -2485,6 +2485,29 @@ fn it_can_trunc() { } } +#[test] +fn it_can_trunc_with_scale() { + let cmp = Decimal::from_str("1.2345").unwrap(); + assert_eq!(Decimal::from_str("1.23450").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("1.234500001").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("1.23451").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("1.23454").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("1.23455").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("1.23456").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("1.23459").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("1.234599999").unwrap().trunc_with_scale(4), cmp); + + let cmp = Decimal::from_str("-1.2345").unwrap(); + assert_eq!(Decimal::from_str("-1.23450").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("-1.234500001").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("-1.23451").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("-1.23454").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("-1.23455").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("-1.23456").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("-1.23459").unwrap().trunc_with_scale(4), cmp); + assert_eq!(Decimal::from_str("-1.234599999").unwrap().trunc_with_scale(4), cmp); +} + #[test] fn it_can_fract() { let tests = &[