C++ - 截断变量文件名中双精度的小数位

C++ - Truncating decimal places of a double inside a variable filename

本文关键字:双精度 小数 文件名 变量 C++      更新时间:2023-10-16

我正在尝试编写一些代码来为仿真数据生成适当的文件名。在这里,我创建了一个字符串 resultfile,它采用文本、整数和双精度并将它们连接成文件名。

这是我的(简化的(当前代码:

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 个或更多双精度时,文件名很快就会变得非常大。我正在尝试将文件名设置为:

"5_mu0.4.csv">

我在这里发现了一个似乎相关的问题:如何在一定数量的小数位(无四舍五入(后截断浮点数?,他们似乎建议:

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";