Convert double/float to string

后端 未结 7 1360
渐次进展
渐次进展 2020-11-29 04:55

I need to convert a floating point number to an equivalent string in decimal (or other base). Conversion at first needs to be done in the format xE+0 where

7条回答
  •  眼角桃花
    2020-11-29 05:17

    The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double.

    Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.

    I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:

    http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6

    If you strip out all the hex float support, infinity/nan support, %g/%f/%e variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.

提交回复
热议问题