0

What's the recommended way to format a float to a string without trailing zeros? to_string() returns "1.350000" as does sprintf. I don't want a fixed amount of decimals...

#include <iostream>
#include <string>

using namespace std;

int main()
{
        string s = to_string(1.35);
        cout << s << endl;
}
XTF
  • 1,091
  • 1
  • 13
  • 31
  • If I remember correctly, it's not possible with string format specifiers, however there's always a solution to remove them manually from resulting string. Also see http://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf – Predelnik Apr 22 '15 at 12:27
  • Possible duplicate of [How to output float to cout without scientific notation or trailing zeros?](https://stackoverflow.com/questions/18881854/how-to-output-float-to-cout-without-scientific-notation-or-trailing-zeros) – phuclv May 29 '18 at 01:16

2 Answers2

5
#include <iostream>
#include <string>
#include <sstream>

using namespace std;
int main() {
    stringstream ss;
    ss << 1.35;
    cout << ss.str();
    return 0;
}
Othman Benchekroun
  • 1,998
  • 2
  • 17
  • 36
2

std::to_string & sprintf does not give you any power to control the number of trailing zero you get when converting a float to a string. Try using std::stringstream instead, you'll have all the options you need to control the trailing zeros.

Mekap
  • 2,065
  • 14
  • 26