如何在 C 中将 double 转换为字符串?

新手上路,请多包涵

我需要将双精度存储为字符串。我知道我可以使用 printf 如果我想显示它,但我只想将它存储在一个字符串变量中,以便以后可以将它存储在地图中(作为 value ,而不是 key )。

原文由 Bill the Lizard 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 893
2 个回答

升压(tm) 方式:

 std::string str = boost::lexical_cast<std::string>(dbl);

标准 C++ 方式:

 std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

注意:不要忘记 #include <sstream>

原文由 Johannes Schaub - litb 发布,翻译遵循 CC BY-SA 3.0 许可协议

C++17 引入了: std::to_chars、std::to_chars_result - cppreference.com

 std::to_chars_result to_chars( char* first, char* last, float       value,
                               std::chars_format fmt, int precision );
std::to_chars_result to_chars( char* first, char* last, double      value,
                               std::chars_format fmt, int precision );
std::to_chars_result to_chars( char* first, char* last, long double value,
                               std::chars_format fmt, int precision );

它提供了快速的低级方法来将浮点数转换为具有某种级别格式控制的字符串。这应该很快,因为没有完成分配,只有特定场景的自定义实现应该更快。

C++20 引入了高级易用的格式字符串(相当于 fmt 库):

std::format - cppreference.com

标准::格式

template< class... Args >
std::string format( /*format_string<Args...>*/ fmt, Args&&... args );

template< class... Args >
std::wstring format( /*wformat_string<Args...>*/ fmt, Args&&... args );

template< class... Args >
std::string format( const std::locale& loc,
                    /*format_string<Args...>*/ fmt, Args&&... args );

template< class... Args >
std::wstring format( const std::locale& loc,
                     /*wformat_string<Args...>*/ fmt, Args&&... args );

这是非常好的和方便的。应该比 sprintf 更快。

原文由 Marek R 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题