@@ -100,22 +100,21 @@ impl Number {
100100 }
101101
102102 /// Convert the number to a string in the given base.
103- pub fn to_string ( mut self , base : u64 ) -> String {
104- if self . is_zero ( ) {
103+ pub fn to_string ( & self , base : u64 ) -> String {
104+ let mut number = self . 0 . clone ( ) ;
105+ if number. is_zero ( ) {
105106 return "0" . to_string ( ) ;
106107 }
107108
108- let scale = self . scale ( ) ;
109-
110109 let mut result = String :: new ( ) ;
111110 if self . 0 . is_negative ( ) {
112111 result. push ( '-' ) ;
113- self . 0 = -self . 0 ;
112+ number = -number ;
114113 }
115114
116115 let base_ilog10 = base. ilog10 ( ) ;
117- let integer_part = self . 0 . with_scale ( 0 ) ;
118- let mut fractional_part = self . 0 - & integer_part;
116+ let integer_part = number . with_scale ( 0 ) ;
117+ let mut fractional_part = number - & integer_part;
119118
120119 if integer_part. is_zero ( ) {
121120 result. push ( '0' ) ;
@@ -145,6 +144,7 @@ impl Number {
145144
146145 result. push ( '.' ) ;
147146 let mut temp = BigDecimal :: one ( ) ;
147+ let scale = self . scale ( ) ;
148148 // The standard doesn't specify how many fractional digits to print.
149149 // Here, we set the scale of the number to the value smallest value of
150150 // i such that: (base ^ i).digits() > scale.
@@ -557,4 +557,11 @@ mod tests {
557557 assert_eq ! ( n. scale( ) , 1 ) ;
558558 assert_eq ! ( n. to_string( 10 ) , "1.0" ) ;
559559 }
560+
561+ #[ test]
562+ fn test_to_string ( ) {
563+ let n = Number :: parse ( "4.5" , 10 ) . unwrap ( ) . negate ( ) ;
564+ assert_eq ! ( n. to_string( 10 ) , "-4.5" ) ;
565+ assert_eq ! ( n. to_string( 10 ) , "-4.5" ) ;
566+ }
560567}
0 commit comments