954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Conversion From Float to String

I have searched the forum , also over internet but i didn't found any understandable method to convert float number to string , Please help Me in conversion.

Majestics
Practically a Master Poster
621 posts since Jul 2007
Reputation Points: 199
Solved Threads: 49
 

look up stringstream. However, note that some floats cannot be completely represented by a stream. Therefore, only a "limited" number of digits will appear in the decimal portion of the string. Consider the float representation of 1/3. I'ts 0.3333... where 3 goes on indefinitely. When converted to a string the number of 3s in the float will be truncated.

Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 

You can use ostringstream from , i use that, although it may not be the easyest way.

#include <sstream>

std::string Convert (float number){
     std::ostringstream buff;
     buff<<number;
     return buff.str();
}


ostringstream and istringstream are basically the same as cout and cin, but they don't print stuff on screen. So you can use them as "anything_to_string converter" (ostringstream), and "string_to_anything converter" (istringstream).

Sci@phy
Posting Whiz in Training
279 posts since Sep 2008
Reputation Points: 110
Solved Threads: 43
 

You can do that:

#include <sstream>

std::string Convert (float number){
     std::ostringstream buff;
     buff<<number;
     return buff.str();
}

but for more precision, include , and add setprecision() in your buff<

TheBeast32
Posting Whiz in Training
236 posts since Dec 2007
Reputation Points: 79
Solved Threads: 6
 

Is there a reason not to use strtod( ) ?

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

>Is there a reason not to use strtod( )?
I can only think of one reason, but it's a doozy. strtod works in the wrong direction. The OP wants a conversion from float-point to string, not string to floating-point.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Oops, read to fast.

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

Have you looked at the function fcvt ... see
here .

On windows its _fcvt_s here

And you can always use sprintf .. its slower but reliable.

stilllearning
Posting Whiz
309 posts since Oct 2007
Reputation Points: 161
Solved Threads: 43
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You