Why does std :: setprecision (6) pass more than six digits in fixed-width mode?

The output of the following code:

#include <limits>
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
#include <sstream>

using namespace std;

inline string lexical_cast(const float arg)
{
    stringstream ss;
    ss << fixed << setprecision(numeric_limits<float>::digits10) << arg;
    if (!ss)
        throw "Conversion failed";

    return ss.str();
}

int main()
{
    cout << numeric_limits<float>::digits10 << '\n';
    cout << lexical_cast(32.123456789) << '\n';
}

is an:

6
32.123455

I expected and wanted:

6
32,1234

because, as far as I know, the degree that a floatcan reliably give me in my system.

How can I convince IOStreams to behave the way I want?

+4
source share
1 answer

"" , , . IOStreams "" .

, ++ 11 std::defaultfloat. " " - , , . ++ 03, s.unsetf(std::ios_base::floatfield). - " ".

+12

Source: https://habr.com/ru/post/1529822/


All Articles