# 将双精度/浮点数转换为字符串 [英] Convert double/float to string

### 问题描述

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 `x` is the floating point number.

The idea I have is to first truncate the floating point number into a temporary integer and then convert that integer into string, and then consider the fractional part, multiply it with `10` while the fractional part does not become `0`. After the fractional part is transferred into the left side of the decimal point, apply the integer to string function again and convert the fraction part to string. Is there a better way, which will be faster than this? Will this method induce any kind of side effects?

To convert the floating point number into exponential representation shall I do the same as above and then adjust the power? Or directly bitmask the IEEE 754 floating point representation and convert each part into string.

### 推荐答案

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.

LGPL MIT 许可下，我在这里有一个非常密集(相当难以阅读)但高效的实现:

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.