C++ convert floating point number to string

2019-06-14 10:49发布

问题:

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