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.

Recommended Answers

All 7 Replies

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.

You can use ostringstream from <sstream>, 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).

You can do that:

#include <sstream>

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

but for more precision, include <iomanip>, and add setprecision(<number of digits of precision>) in your buff<<number. Like "buff << setprecision(32) << number;"

Is there a reason not to use strtod( )?

>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.

Oops, read to fast.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.