How to convert a floating point into a string and add the 2 decimals when the floating point is a round number. Currently I am using the following, but for round numbers, I would like to have the .00 added. Do I need to write my own routine for that?
float floatingNumber = 1.00;
string string;
ostringstream stream;
stream << floatingNumber;
string += stream.str(); // result is 1 not 1.00
You should set precision manually and use flag, that allows you to use fixed notation
stream << std::fixed << std::setprecision(2) << floatingNumber;
if you are using c++11, you can convert a float to std::string using std::to_string()
float f(0.5f);
std::string str = std::to_string(f);
Same thing using auto :
auto f(0.5f); // f is a float
auto str = std::to_string(f); // str is a std::string
However, you'll have to handle the precision manually.
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.