2

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
Michel de Man
  • 223
  • 1
  • 3
  • 10
  • 2
    `float floatingNumber = 1.00;` is identical to `float floatingNumber = 1;` – David Heffernan May 16 '13 at 08:36
  • possible duplicate of [Precise floating-point<->string conversion](http://stackoverflow.com/questions/1311242/precise-floating-point-string-conversion) – Joris Timmermans May 16 '13 at 08:44
  • @MadKeithV: Similar, but that is not the same issue. It deals with the (mathematically real) difference between 1.34 and 1.340000000001. This deals with the (mathematically non-existent) difference between 1 and 1.00. – MSalters May 16 '13 at 09:57

2 Answers2

7

You should set precision manually and use flag, that allows you to use fixed notation

setprecision fixed

stream << std::fixed << std::setprecision(2) << floatingNumber;
ForEveR
  • 55,233
  • 2
  • 119
  • 133
1

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.

Cyril Leroux
  • 2,599
  • 1
  • 26
  • 25