Skip to content

Commit

Permalink
fix: decimal round_dp on zero with too large dp (#575)
Browse files Browse the repository at this point in the history
Co-authored-by: jon-chuang <jon-chuang@users.noreply.github.com>
  • Loading branch information
jon-chuang and jon-chuang committed Feb 9, 2023
1 parent 84f5943 commit c205456
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,14 @@ impl Decimal {
/// ```
#[must_use]
pub fn round_dp_with_strategy(&self, dp: u32, strategy: RoundingStrategy) -> Decimal {
let old_scale = self.scale();

// return early if decimal has a smaller number of fractional places than dp
// e.g. 2.51 rounded to 3 decimal places is 2.51
if old_scale <= dp {
return *self;
}

// Short circuit for zero
if self.is_zero() {
return Decimal {
Expand All @@ -1284,14 +1292,6 @@ impl Decimal {
};
}

let old_scale = self.scale();

// return early if decimal has a smaller number of fractional places than dp
// e.g. 2.51 rounded to 3 decimal places is 2.51
if old_scale <= dp {
return *self;
}

let mut value = [self.lo, self.mid, self.hi];
let mut value_scale = self.scale();
let negative = self.is_sign_negative();
Expand Down
9 changes: 9 additions & 0 deletions tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2471,6 +2471,15 @@ fn it_can_round_complex_numbers() {
assert_eq!("0.16", part.to_string());
}

#[test]
fn it_does_not_round_decimals_to_too_many_dp() {
// Issue 574
let zero = Decimal::new(0, 28);
let rounded = zero.round_dp(32);
assert_eq!(rounded.scale(), 28); // If dp > old_scale, we retain the old scale.
rounded.to_string();
}

#[test]
fn it_can_round_down() {
let tests = &[
Expand Down

0 comments on commit c205456

Please sign in to comment.