C++ - 截断变量文件名中双精度的小数位
C++ - Truncating decimal places of a double inside a variable filename
我正在尝试编写一些代码来为仿真数据生成适当的文件名。在这里,我创建了一个字符串 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";
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 打印双精度的整个非小数部分
- 将字符串转换为双精度,而字符串有 N 位小数,C++
- C++ std::流双精度值没有科学,也没有固定的小数计数
- 小数、双精度、整数等数据类型的范围
- 在C++中使用atof将带小数的字符串转换为双精度字符串
- 如何打印具有正确有效小数位数的C++双精度
- 使用 C++ 中的按位运算隔离双精度的小数部分
- 基元浮点和双精度支持小数位数
- 如何在Qt中打印所有小数的双精度
- 双精度不能正确减去小数
- C++ 如何获取兰登数以及如何保存带有 ONY 两位小数的双精度
- 双精度-小数位数
- 如何检查双精度数是否有小数部分
- 从二进制文件读取双精度(到类中)-小数不显示
- 将表示小数的 int 转换为双精度的正确方法是什么
- 如何砍掉双精度值的几个小数