Skip to content

Commit 9520e96

Browse files
committed
Add BigDecimal::with_precision_round method
1 parent d1bfee2 commit 9520e96

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/lib.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,21 @@ impl BigDecimal {
426426
}
427427
}
428428

429+
/// Return this BigDecimal with the given precision, rounding if needed
430+
pub fn with_precision_round(&self, prec: stdlib::num::NonZeroU64, round: RoundingMode) -> BigDecimal {
431+
let digit_count = self.digits();
432+
let new_prec = prec.get().to_i64();
433+
let new_scale = new_prec
434+
.zip(digit_count.to_i64())
435+
.map(|(new_prec, old_prec)| new_prec.checked_sub(old_prec))
436+
.flatten()
437+
.map(|prec_diff| self.scale.checked_add(prec_diff))
438+
.flatten()
439+
.expect("precision overflow");
440+
441+
self.with_scale_round(new_scale, round)
442+
}
443+
429444
/// Return the sign of the `BigDecimal` as `num::bigint::Sign`.
430445
///
431446
/// ```

0 commit comments

Comments
 (0)