1

I would like to append a float to a string with the default iostream float format e.g 4.2f the following way:

std::string s;
s.append("float format: ");
s.append(std::to_string((float) 4.3)));
s.append(" : end");

I would like to find a function to generate the following result:

float format: 4.3f : end

But the code above gives me this result instead:

float format: 4.300000000000 : end

I have to format and then put in the string. I don't want to format when pushing on iostream.

Justin
  • 24,288
  • 12
  • 92
  • 142
Romain-p
  • 518
  • 2
  • 9
  • 26

1 Answers1

2

Found a way using stringstream :) Then it uses the default ostream float format and pushes it to a string :)

std::stringstream ss;
std::string s;
ss << 3.4;
ss >> s;
std::cout << s.append("f") << std::endl;

generates the following output:

3.4f
Romain-p
  • 518
  • 2
  • 9
  • 26