@@ -629,19 +629,17 @@ impl BigDecimal {
629
629
return result. with_prec ( 100 ) ;
630
630
}
631
631
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 ( )
640
636
}
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 ( ) ;
641
639
let trunc_to = digits. len ( ) - trailing_count as usize ;
642
640
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 ;
645
643
BigDecimal :: new ( int_val, scale)
646
644
}
647
645
}
@@ -1974,7 +1972,7 @@ mod bigdecimal_serde {
1974
1972
#[ cfg( test) ]
1975
1973
mod bigdecimal_tests {
1976
1974
use BigDecimal ;
1977
- use traits:: { ToPrimitive , FromPrimitive } ;
1975
+ use traits:: { ToPrimitive , FromPrimitive , Zero } ;
1978
1976
use std:: convert:: TryFrom ;
1979
1977
use std:: str:: FromStr ;
1980
1978
use num_bigint;
@@ -2846,10 +2844,17 @@ mod bigdecimal_tests {
2846
2844
( BigDecimal :: new( BigInt :: from( 1_900_000 ) , 3 ) ,
2847
2845
BigDecimal :: new( BigInt :: from( 19 ) , -2 ) ,
2848
2846
"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" ) ,
2849
2853
] ;
2850
2854
2851
2855
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) ;
2853
2858
assert_eq ! ( normalized. to_string( ) , string) ;
2854
2859
}
2855
2860
}
0 commit comments