C ++将浮点数转换为字符串 [英] C++ convert floating point number to string

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

问题描述

我试图将浮点数转换为字符串。我知道你可以使用ostringstream& sprintf等,但在项目中,我正在工作,我试图使用自己的函数(我创建自己的字符串类,而不使用任何外部函数)。我不想要一个完美的表示,例如。我不介意它,如果这发生大或小数字:1.0420753e + 4喜欢它与标准stringstream。

I am trying to convert a floating point number to string. I know you can do it using ostringstream & sprintf etc. but in the project I am working I am trying to do it using my own functions only (I am creating my own string class without using any outside functions). I don't want a perfect representation e.g. I don't mind it if this happens with large or small number: 1.0420753e+4 like it does with the standard stringstream.

我知道浮点数如何工作例如符号,指数,尾数),以及它们如何以与它们显示的不同的方式表示(这就是为什么它的困难)。我知道这是可能的,因为std c ++库可以做到 - 我只是不知道如何做自己

I know how floating point numbers work (e.g. sign, exponent, mantissa) and how they are represented in a different way from what they are displayed as (that is why its difficult). I know this is possible because the std c++ library can do it - I just don't know how to do it myself.

我已经创建了自己的整数版本(将int转换为我自己的CString类)。

I have created my own integer version of this (converts int to my own CString class).

推荐答案

自己。 iOS有标准的C ++功能,用于格式化浮点对象,我希望Android也是。

First, do not do this yourself. iOS has standard C++ features for formatting floating-point objects, and I expect Android does too.

其次,不要自己做。这是很难做不舍入错误。执行它的技术是已知的和已发布的,你应该使用好的引用,而不是通常在Stack Overflow上找到的算法。这篇文章的经典论文是 David M. Gay正确圆整的二进制 - 十进制和十进制二进制转换,这里是来自David Gay的代码

Second, do not do this yourself. It is hard to do without rounding errors. The techniques for doing it are already known and published, and you should use good references rather than the algorithms you will generally find on Stack Overflow. The classic paper for this is Correctly Rounded Binary-Decimal and Decimal-Binary Conversions by David M. Gay, and here is code from David Gay.

这篇关于C ++将浮点数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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