C++ 转换浮点值时设置 std::to_string 的精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16605967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:29:32 来源:igfitidea点击:
Set precision of std::to_string when converting floating point values
提问by learnvst
回答by hmjd
There is no way to change the precision via to_string()
but the setprecision
IO manipulator could be used instead:
无法通过以下方式更改精度,to_string()
但setprecision
可以使用 IO 操纵器:
#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();
}