C++ 如何使用 std::string 格式化浮点数

C++ How do I format a float with std::string?

本文关键字:string 浮点数 格式化 std 何使用 C++      更新时间:2023-10-16

我想通过以下方式将浮点数附加到具有默认 iostream 浮点格式的字符串中,例如 4.2f:

std::string s;
s.append("float format: ");
s.append(std::to_string((float) 4.3)));
s.append(" : end");

我想找到一个函数来生成以下结果:

float format: 4.3f : end

但是上面的代码给了我这个结果:

float format: 4.300000000000 : end

我必须格式化,然后放入字符串。我不想在推动iostream时格式化。

找到了使用字符串流:)的方法然后它使用默认的 ostream 浮点格式并将其推送到字符串:)

std::stringstream ss;
std::string s;
ss << 3.4;
ss >> s;
std::cout << s.append("f") << std::endl;

生成以下输出:

3.4f