views:

48

answers:

1

I need to represent single precision numbers as text in a way that won't lose any information (so I can get the same number back, possibly disregarding NaNs etc.), but without too many spurious digits - so single precision 0.1 comes out as "0.1" not "0.100000001490116".

I'm not trying to save bytes, these extra digits are just confusing.

Is there a simple way to do that? I can see at least 8 significant decimal digits will be needed to represent 23+1 bits (12345678.0 and 12345679.0 are different in single precision), and that it would be enough with binary exponent (12345b-11 sort of notation) but is this guaranteed to be enough decimal exponent notation (1.2345e+6) or one that uses 0-padding (0.0000123456 - usually more readable, and these zeroes don't bother me much)?

Any printf formats, or exact instructions much appreciated.

+3  A: 

Doing this right is a very non-trivial task: the problem is the subject of multiple academic papers.

Many open source projects use David M. Gay's dtoa.c library for this. If you use Python, dtoa.c-based rounding was recently (2.7/3) released, and the discussion on the relevant task discussion is very worthwhile:

If you want to know (lots) more:

Piet Delport
Ouch, this looks a lot messier than I expected. Fortunately I don't need perfect representation every time, so I'll just try low-precision conversion with `"%g"`, and if it doesn't convert back to correct answer I'll fall back to standard library code with all spurious digits.
taw