转换双人/浮点数到字符串 [英] Convert Double/Float to string
问题描述
我需要一个浮点数转换为等效的字符串十进制(或其他碱)。转换首先,需要在格式做 XE + 0
,其中 X
是浮点数。
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.
这个想法我已经是浮点数首先截断到一个临时整数,则该整数转换成字符串,然后再考虑小数部分,用 10
而小数部分不会成为 0
。小数部分被转移到小数点的左边后,再次应用整数字符串功能和分数部分转换为字符串。有没有更好的办法,这将是比这个更快?这种方法将促使任何种类的副作用?
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?
要转换浮点数为指数重新presentation我该怎么同上,然后调整电源?或者直接在位掩码IEEE754浮点重新presentation,每个部分转换成字符串。
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 IEEE754 floating point representation and convert each part into string.
的注:没有其他功能可以使用的,因为我有机会获得绝对没有库函数。这code进入玩具内核。的
推荐答案
唯一确切的解决方案是为基数转换执行arbitrary- precision小数运算,因为准确的值可以非常长 - 80位长双
,高达约10000位小数。幸运的是它的只有高达约700位左右的IEEE 双击
。
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
.
,而不是与个别十进制数字的工作,这是有益的,而不是工作基-1-十亿(最高功率的10,适合在一32位整数),然后这些基-1-十亿数字转换为9十进制数字每个在你计算结束。
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
如果你去掉所有的十六进制浮点支持,无限/楠支持,%G
/ %F
/ %E
变化的支持,倒圆(这将永远不会被需要,如果你只想要确切的答案),你可能不需要其他的东西,剩下的code是相当简单
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.
这篇关于转换双人/浮点数到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!