我正在尝试编写一些代码来为模拟数据生成适当的文件名。在这里,我创建了一个字符串 resultfile,它接受文本、整数和 double 并将它们连接成一个文件名。
这是我的(简化的)当前代码:
string resultfile;
int Nx = 5;
double mu = 0.4;
//Simulation code here
resultfile += to_string(Nx) + "_mu" + to_string(mu) + ".csv";
ofstream myfile;
myfile.open ("./Datasets/"+ resultfile);
myfile << SimulationOutputs;
myfile.close();
这会将一个 .csv 文件保存到我的/Datasets/文件夹,但是,数据的文件名最终为:
“5_mu0.4000000.csv”
当您的文件标题包含 2 个或更多 double 时,文件名很快就会变得非常大。我正在尝试将文件名设为:
“5_mu0.4.csv”
我在这里发现了一个似乎相关的问题:How to truncate a floating point number after a certain number of decimal places (no rounding)? ,他们似乎建议:
to_string(((int)(100 * mu)) / 100.0)
但是,此编辑不会更改我的数据输出的文件名。我是 C++ 的新手,所以这里可能有一个对我来说并不明显的明显解决方案。
最佳答案
你不能设置 std::to_string
的精度,你可以自己写,比如:
#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();
}
然后
resultfile += std::to_string(Nx) + "_mu" + to_string_with_precision(mu, 2) + ".csv";
关于C++ - 截断变量文件名中 double 的小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50497751/