Skip to content

Commit 13a732f

Browse files
committed
Merge pull request akubera#64 from leoyvens/fix-normalize
2 parents 46451ce + 60ea67a commit 13a732f

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

src/lib.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -629,19 +629,17 @@ impl BigDecimal {
629629
return result.with_prec(100);
630630
}
631631

632-
pub fn normalize(&self) -> BigDecimal {
633-
let (_, mut digits) = self.int_val.to_u32_digits();
634-
let mut trailing_count = 0;
635-
{
636-
let mut digits_iter = digits.iter().rev();
637-
while digits_iter.next() == Some(&0) {
638-
trailing_count += 1;
639-
}
632+
#[must_use]
633+
pub fn normalized(&self) -> BigDecimal {
634+
if self == &BigDecimal::zero() {
635+
return BigDecimal::zero()
640636
}
637+
let (sign, mut digits) = self.int_val.to_radix_be(10);
638+
let trailing_count = digits.iter().rev().take_while(|i| **i == 0).count();
641639
let trunc_to = digits.len() - trailing_count as usize;
642640
digits.truncate(trunc_to);
643-
let int_val = BigInt::new(self.sign(), digits);
644-
let scale = self.scale - trailing_count;
641+
let int_val = BigInt::from_radix_be(sign, &digits, 10).unwrap();
642+
let scale = self.scale - trailing_count as i64;
645643
BigDecimal::new(int_val, scale)
646644
}
647645
}
@@ -1974,7 +1972,7 @@ mod bigdecimal_serde {
19741972
#[cfg(test)]
19751973
mod bigdecimal_tests {
19761974
use BigDecimal;
1977-
use traits::{ToPrimitive, FromPrimitive};
1975+
use traits::{ToPrimitive, FromPrimitive, Zero};
19781976
use std::convert::TryFrom;
19791977
use std::str::FromStr;
19801978
use num_bigint;
@@ -2846,10 +2844,17 @@ mod bigdecimal_tests {
28462844
(BigDecimal::new(BigInt::from(1_900_000), 3),
28472845
BigDecimal::new(BigInt::from(19), -2),
28482846
"1900"),
2847+
(BigDecimal::new(BigInt::from(0), -3),
2848+
BigDecimal::zero(),
2849+
"0"),
2850+
(BigDecimal::new(BigInt::from(0), 5),
2851+
BigDecimal::zero(),
2852+
"0"),
28492853
];
28502854

28512855
for (not_normalized, normalized, string) in vals {
2852-
assert_eq!(not_normalized.normalize(), normalized);
2856+
assert_eq!(not_normalized.normalized(), normalized);
2857+
assert_eq!(not_normalized.normalized().to_string(), string);
28532858
assert_eq!(normalized.to_string(), string);
28542859
}
28552860
}

0 commit comments

Comments
 (0)