Skip to content

Commit 8e532ee

Browse files
author
Daniel Kroening
committed
get closer to what implementations do with %g
1 parent 41bc492 commit 8e532ee

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

src/util/ieee_float.cpp

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -161,25 +161,39 @@ std::string ieee_floatt::format(const format_spect &format_spec) const
161161

162162
case format_spect::stylet::AUTOMATIC:
163163
{
164+
// On Linux, the man page says:
164165
// "Style e is used if the exponent from its conversion
165166
// is less than -4 or greater than or equal to the precision."
167+
//
168+
// On BSD, it's
169+
// "The argument is printed in style f (F) or in style e (E)
170+
// whichever gives full precision in minimum space."
166171

167172
mp_integer _exponent, _fraction;
168173
extract_base10(_fraction, _exponent);
169174

170-
if(_exponent>=0)
175+
mp_integer adjusted_exponent=base10_digits(_fraction)+_exponent;
176+
177+
if(adjusted_exponent>=format_spec.precision ||
178+
adjusted_exponent<-4)
171179
{
172-
if(base10_digits(_fraction)+_exponent>=format_spec.precision)
173-
result+=to_string_scientific(format_spec.precision);
174-
else
175-
result+=to_string_decimal(format_spec.precision);
180+
result+=to_string_scientific(format_spec.precision);
176181
}
177-
else // _exponent<0
182+
else
178183
{
179-
if(true) // base10_digits(fraction)+_exponent<-4)
180-
result+=to_string_scientific(format_spec.precision);
181-
else
182-
result+=to_string_decimal(format_spec.precision);
184+
result+=to_string_decimal(format_spec.precision);
185+
186+
// Implementations tested also appear to suppress trailing zeros
187+
// and trailing dots.
188+
189+
{
190+
std::size_t trunc_pos=result.find_last_not_of('0');
191+
if(trunc_pos!=std::string::npos)
192+
result.resize(trunc_pos+1);
193+
}
194+
195+
if(!result.empty() && result.back()=='.')
196+
result.resize(result.size()-1);
183197
}
184198
}
185199
break;

0 commit comments

Comments
 (0)