简体   繁体   中英

Float64 to string

In C++, how can I convert a data of type float64 to a string without losing any of the data in float64? I need it to not only be converted to a string, but add a string to either side of the number and then sent to be written in a file.

Code:

string cycle("---NEW CYCLE ");
cycle+=//convert float64 to string and add to cycle
cycle+= "---\r\n";
writeText(cycle.c_str()); //writes string to txt file

Thanks.

The usual way of converting numbers to std::string s is to use std::ostringstream .

std::string stringify(float value)
{
     std::ostringstream oss;
     oss << value;
     return oss.str();
}

    // [...]
    cycle += stringify(data);

您可以使用sprintf格式化字符串。

You should use sprintf . See documentation here C++ Reference .

As an example it would be something like:

char str[30];
float flt = 2.4567F;
sprintf(str, "%.4g", flt ); 

Also I would use string::append to add the string. See here .

UPDATE

Updated code according to comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM