@@ -117,6 +117,11 @@ pub unsafe fn write<W: io::Write>(wr: &mut W, positive: bool, mut n: u64, expone
117117 }
118118
119119 // Not easily printable, write down fraction, then full number, then exponent
120+
121+ // Since we move the decimal point right after the first digit, we have to adjust the
122+ // exponent part. If the number is long enough, this may result in the exponent switching
123+ // sign from negative to positive - we have to handle this case separately.
124+ let mut exponent_positive = false ;
120125 if n < 10 {
121126 // Single digit, no fraction
122127 curr -= 1 ;
@@ -154,16 +159,24 @@ pub unsafe fn write<W: io::Write>(wr: &mut W, positive: bool, mut n: u64, expone
154159 ptr:: copy_nonoverlapping ( lut_ptr. offset ( d1) , buf_ptr. offset ( curr) , 2 ) ;
155160 }
156161
157- // Substract the amount of digits printed in the fraction
158- // from the exponent that we still need to print using
159- // the `e` notation
160- e -= buf. len ( ) as u16 - curr as u16 ;
162+ let printed_so_far = buf. len ( ) as u16 - curr as u16 ;
163+
164+
165+ if printed_so_far <= e {
166+ // Subtract the amount of digits printed in the fraction
167+ // from the exponent that we still need to print using
168+ // the `e` notation
169+ e -= printed_so_far;
170+ } else {
171+ // Same as e = |e - printed_so_far|.
172+ e = printed_so_far - e;
173+ exponent_positive = true ;
174+ }
161175
162176 curr -= 1 ;
163177 * buf_ptr. offset ( curr) = b'.' ;
164178
165179 write_num ( & mut n, & mut curr, buf_ptr, lut_ptr) ;
166-
167180 }
168181
169182 // Write out the number with a fraction
@@ -174,8 +187,16 @@ pub unsafe fn write<W: io::Write>(wr: &mut W, positive: bool, mut n: u64, expone
174187 )
175188 ) ) ;
176189
177- // Write the remaining `e` notation
178- try!( wr. write_all ( b"e-" ) ) ;
190+ // Omit the 'e' notation for e == 0
191+ if e == 0 {
192+ return Ok ( ( ) ) ;
193+ }
194+ // Write the remaining `e` notation, with proper sign
195+ if exponent_positive {
196+ wr. write_all ( b"e+" ) ?;
197+ } else {
198+ wr. write_all ( b"e-" ) ?;
199+ }
179200 return write ( wr, true , e as u64 , 0 ) ;
180201
181202 }
0 commit comments