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

查看:31
本文介绍了将双精度/浮点数转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将浮点数转换为十进制(或其他基数)的等效字符串.首先需要以 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?

要将浮点数转换为指数表示,我应该像上面一样做然后调整幂吗?或者直接对 IEEE 754 浮点表示进行位掩码,并将每个部分转换为字符串.

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.

注意:不能使用其他函数,因为我绝对不能访问任何库函数.这段代码进入了一个玩具内核.

推荐答案

唯一的精确解决方案是对基转换执行任意精度的十进制算术,因为精确值可以是非常长 -对于 80 位 long double,最多约 10000 个小数位.幸运的是,对于 IEEE double,它仅"多达 700 个左右的位置.

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.

而不是使用单个十进制数字,而是使用十亿基数(适合 32 位整数的 10 的最高幂)然后将这些十亿基数"转换为 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 变体支持,四舍五入(如果您只想要确切的答案,则永远不需要)和其他您可能不需要的东西,剩下的代码相当简单.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆