C++ convert floating point number to string

家住魔仙堡 提交于 2019-12-23 04:24:46

问题


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.

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.

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


回答1:


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

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.




回答2:


Simple method: Divide by 10 until the value is ≤ 1. This gives you the number of decimals after which you should print the .. Multiply the original number by 10 for each digit you want after the ., and round. Stringify the resulting integer, and insert the ..




回答3:


Use ostringstream -:

double d = 2.7818; 
std::ostringstream ss;
ss << d;
std::cout << ss.str() << std::endl;



回答4:


Uhm, if you really want to reinvent your own square wheel, then probably the easiest way is to write converter from float to int(you said you know how bit pattern works), or maybe even 2 ints - one for fractional part, other for the rest, then print them REUSING code that already exists



来源:https://stackoverflow.com/questions/17363196/c-convert-floating-point-number-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!