@@ -100,22 +100,21 @@ impl Number {
100
100
}
101
101
102
102
/// 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 ( ) {
105
106
return "0" . to_string ( ) ;
106
107
}
107
108
108
- let scale = self . scale ( ) ;
109
-
110
109
let mut result = String :: new ( ) ;
111
110
if self . 0 . is_negative ( ) {
112
111
result. push ( '-' ) ;
113
- self . 0 = -self . 0 ;
112
+ number = -number ;
114
113
}
115
114
116
115
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;
119
118
120
119
if integer_part. is_zero ( ) {
121
120
result. push ( '0' ) ;
@@ -145,6 +144,7 @@ impl Number {
145
144
146
145
result. push ( '.' ) ;
147
146
let mut temp = BigDecimal :: one ( ) ;
147
+ let scale = self . scale ( ) ;
148
148
// The standard doesn't specify how many fractional digits to print.
149
149
// Here, we set the scale of the number to the value smallest value of
150
150
// i such that: (base ^ i).digits() > scale.
@@ -557,4 +557,11 @@ mod tests {
557
557
assert_eq ! ( n. scale( ) , 1 ) ;
558
558
assert_eq ! ( n. to_string( 10 ) , "1.0" ) ;
559
559
}
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
+ }
560
567
}
0 commit comments