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

c++stringc++11doublefloating

提问by learnvst

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

在 C++11 中,当给定类型为or的输入值时, std:: to_string默认为 6 个小数位。更改此精度的推荐或最优雅的方法是什么?floatdouble

回答by hmjd

There is no way to change the precision via to_string()but the setprecisionIO 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();
}