Decimal points with std::stringstream?

57,576

Solution 1

I think that your problem is that precision() sets the precision used in future stream insertion operations, not when generating the final string to present. That is, by writing

ta << a;
tb << b;
tc << c;

ta.precision(2);
tb.precision(2);
tc.precision(2);

You're setting precision too late, as the first three lines have already converted the floating point numbers to strings using the default precision.

To fix this, try changing the order in which you execute these statements to

ta.precision(2);
tb.precision(2);
tc.precision(2);

ta << a;
tb << b;
tc << c;

This will cause the writes into the stringstream to use your custom precision rather than the existing defaults.

However, the effect of the precision modifier is only meaningful if you explicitly tell the stream that you want to use either fixed-precision or scientific notation for output. To do this, you can use either the fixed or scientific modifiers:

ta.precision(2);
tb.precision(2);
tc.precision(2);

ta << fixed << a;
tb << fixed << b;
tc << fixed << c;

This will correctly display the appropriate number of digits.

On a related note, you don't need to use three stringstreams to accomplish your goal. You can just use one:

std::stringstream t;
t.precision(2);

t << fixed << a << '\n' << b << '\n' << c << '\n';

std::string out = t.str();

Solution 2

In C++20 you can use std::format which is move efficient and less verbose than std::stringstream:

float a = 5.23;
float b = 3.134;
float c = 3.0;
std::string out = std::format("{:.2f}\n{:.2f}\n{:.2f}\n", a, b, c);

In the meantime you can use the {fmt} library, std::format is based on (godbolt).

Disclaimer: I'm the author of {fmt} and C++20 std::format.

Share:
57,576
noobcpp
Author by

noobcpp

Updated on March 03, 2021

Comments

  • noobcpp
    noobcpp almost 3 years

    I have a bunch of integers that I put into stringstreams. Now I want to change the stringstreams into strings while keeping a constant precision with the strings. How would I do that? I know I can use stringstreams.precision(), but it's not working for some reason:

    float a = 5.23;
    float b = 3.134;
    float c = 3.0;
    
    std::stringstream ta;
    std::stringstream tb;
    std::stringstream tc;
    
    ta << a;
    tb << b;
    tc << c;
    
    ta.precision(2);
    tb.precision(2);
    tc.precision(2);
    
    std::string out = "";
    out += ta.str() + "\n";
    out += tb.str() + "\n";
    out += tc.str() + "\n";
    

    Will return 5.23\n3.134\n3.0, rather than 5.23\n3.13\n3.00