double and stringstream formatting

前端 未结 4 1459
半阙折子戏
半阙折子戏 2021-02-19 08:39
double val = 0.1;
std::stringstream ss;
ss << val;
std::string strVal= ss.str();

In the Visual Studio debugger, val has the value 0.

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 09:09

    You can change the floating-point precision of a stringstream as follows:

    double num = 2.25149;
    std::stringstream ss(stringstream::in | stringstream::out);
    ss << std::setprecision(5) << num << endl;
    ss << std::setprecision(4) << num << endl;
    

    Output:

    2.2515
    2.251
    

    Note how the numbers are also rounded when appropriate.

提交回复
热议问题