Skip to content

Commit

Permalink
Introduce trunc_with_scale
Browse files Browse the repository at this point in the history
  • Loading branch information
c410-f3r committed Feb 28, 2023
1 parent caee892 commit 8ae854a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = &[
Expand Down

0 comments on commit 8ae854a

Please sign in to comment.