在转换浮点值时设置std :: to_string的精度 [英] Set precision of std::to_string when converting floating point values
本文介绍了在转换浮点值时设置std :: to_string的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++ 11中,std :: to_string 在给定时默认为6位小数一个输入值为 float
或 double
的输入值。什么是推荐或最优雅的方法来改变这个精度?
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?
推荐答案
没有办法通过 to_string()
,但 setprecision
可以使用IO操纵器:
There is no way to change the precision via to_string()
but the setprecision
IO manipulator could be used instead:
#include <sstream>
#include <iomanip>
template <typename T>
std::string to_string_with_precision(const T a_value, const int n = 6)
{
std::ostringstream out;
out << std::setprecision(n) << a_value;
return out.str();
}
这篇关于在转换浮点值时设置std :: to_string的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文