c++ - 将 float 舍入为 2 位小数以将其写入文本文件

标签 c++ file decimal precision

我正在做一个学校项目,我必须将一个 float 写入一个文本文件。 问题是我只想将最多 2 位小数的 float 写入文件。 我在互联网上搜索了很多,但只找到了流的“setprecision”函数。

我不能那样做,因为我不想打印它,但我想将它写入一个只有 2 位小数的文件。所以我必须首先将 float 转换为相同的数字但只有 2 位小数,然后我将它放入一个字符串(已经包含其他字符)。然后我将该字符串写入输出文件。

我在“ofstream”的描述中发现了一个方法“precision”,但我认为它不适用于我正在尝试做的事情。 (http://www.cplusplus.com/reference/fstream/ofstream/)

有谁知道执行此操作的函数或执行此操作的方式吗?

感谢您的帮助!

最佳答案

I can't do that because I don't want to print it but i want to write it to a file with only 2 decimals.

ostream 不仅仅用于打印。您可以对 ofstream 执行与使用 cout 相同的操作。

std::ofstream fout("out.txt");

fout << std::setprecision(2) << 1.23456;

That function makes a string that contains the price with the name of the article and the rest of the information I want. The function returns that string and then I write that string to the output file

好吧,您可以通过将 ostream 引用传递给函数来编写输出,而不是取回字符串。您还可以让函数在将 float 写入字符串时只进行格式化。 Ostreams 不仅仅用于打印或写入文件:

std::stringstream ss;

ss << std::setprecision(2) << 1.23456;

std::string s = ss.str();

关于c++ - 将 float 舍入为 2 位小数以将其写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562476/

相关文章:

按特定时间过滤日志文件的Python代码

c - 将无限长的 base 2^32 数字转换为可打印的 base 10 的算法

c++ - Linux中的UDP sendto是否会返回ENOBUFS?

java - 在 Scala 中,是否有一种安全、快捷的方式将 InputStream 写入文件?

c++ - 模板类内部运算符在该类的不同特化对象之间的特化

c# - 从 .txt 文件中读取数据,然后将数据导出到 DataGridView

decimal - 解构神奇宝贝故障?

c# - 如何将字符串转换为整数或小数?

c++ - 为什么有一个类是 std::is_trivially_copyable 而不是 std::is_trivially_copy_constructible 可以与 memcpy 一起使用

c++ - 在 C++ 中编写函数来乘以矩阵