Skip to content

Commit 1161ca9

Browse files
committed
Fix round() panic if self.digits() > 16
1 parent 42e4b85 commit 1161ca9

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -582,27 +582,26 @@ impl BigDecimal {
582582
}
583583

584584
/// Return number rounded to round_digits precision after the decimal point
585-
/// panic if self.digits() > 16
586585
fn round(&self, round_digits: i64) -> BigDecimal {
587586
let (bigint, decimal_part_digits) = self.as_bigint_and_exponent();
588587
let need_to_round_digits = decimal_part_digits - round_digits;
589588
if round_digits >= 0 && need_to_round_digits <= 0 {
590589
return self.clone();
591590
}
592591

593-
let mut number = bigint.to_i64().unwrap();
594-
// avoid -1555 / 10 = -156
592+
let mut number = bigint.to_i128().unwrap();
595593
if number < 0 {
596594
number = -number;
597595
}
598-
for _ in 0..(need_to_round_digits-1) {
596+
for _ in 0..(need_to_round_digits - 1) {
599597
number /= 10;
600598
}
601599
let digit = number % 10;
600+
602601
if digit <= 4 {
603602
self.with_scale(round_digits)
604603
} else {
605-
if bigint.sign() == Sign::Minus {
604+
if bigint.is_negative() {
606605
self.with_scale(round_digits) - BigDecimal::new(BigInt::from(1), round_digits)
607606
} else {
608607
self.with_scale(round_digits) + BigDecimal::new(BigInt::from(1), round_digits)
@@ -2583,6 +2582,7 @@ mod bigdecimal_tests {
25832582
("-1.4499999999", 1, "-1.4"),
25842583
("1.449999999", 1, "1.4"),
25852584
("-9999.444455556666", 10, "-9999.4444555567"),
2585+
("-12345678987654321.123456789", 8, "-12345678987654321.12345679"),
25862586
];
25872587
for &(x, digits, y) in test_cases.iter() {
25882588
let a = BigDecimal::from_str(x).unwrap();

0 commit comments

Comments
 (0)