Set precision of std::to_string when converting floating point values [duplicate]

北城以北 提交于 2019-11-26 09:35:07

问题


This question already has an answer here:

  • The precision of std::to_string(double) 3 answers

In C++11, std::to_string defaults to 6 decimal places when given an input value of type float or double. What is the recommended, or most elegant, method for changing this precision?


回答1:


There is no way to change the precision via to_string() but the setprecision IO manipulator could be used instead:

#include <sstream>

template <typename T>
std::string to_string_with_precision(const T a_value, const int n = 6)
{
    std::ostringstream out;
    out.precision(n);
    out << std::fixed << a_value;
    return out.str();
}


来源:https://stackoverflow.com/questions/16605967/set-precision-of-stdto-string-when-converting-floating-point-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!