在 C++ 中将浮点数转换为 std::string

2022-01-12 00:00:00 type-conversion c++

我有一个浮点值需要放入 std::string.如何从浮点数转换为字符串?

I have a float value that needs to be put into a std::string. How do I convert from float to string?

float val = 2.5;
std::string my_val = val; // error here

推荐答案

除非你担心性能,否则使用 字符串流:

Unless you're worried about performance, use string streams:

#include <sstream>
//..

std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());

如果您对 Boost 没问题,lexical_cast<> 是一个方便的选择:

If you're okay with Boost, lexical_cast<> is a convenient alternative:

std::string s = boost::lexical_cast<std::string>(myFloat);

有效的替代品是例如FastFormat 或简单的 C 风格函数.

Efficient alternatives are e.g. FastFormat or simply the C-style functions.

相关文章