【问题标题】:Conversion from double to string in c++ [duplicate]在c ++中从双精度转换为字符串[重复]
【发布时间】:2020-05-28 18:00:53
【问题描述】:

我目前正在为我的计算机科学模块编写一个项目,但如果双精度值中有太多小数位,我的字符串值会默认为科学计数法。

我已经用ostringstream.str() 尝试了明显的解决方案,但它变成了符号。我必须编译到 C++98 标准,所以我不能使用像 std::to_string 这样的现代解决方案。

我需要将值转换为字符串,但它需要保持其格式。任何帮助将不胜感激。

【问题讨论】:

标签: c++ string type-conversion double scientific-notation


【解决方案1】:

我会使用:

std::to_string(myDouble);

【讨论】:

  • 不幸的是需要 C++11
  • 在 2020 年,如果您无法访问 C++11,那真是不幸。碰巧,我维护了一些相当老的 C++ 代码,我的组织不允许我更改,但我只根据需要用 C++03 或 C++98 编写新的东西,而且只有在有非常非常好的理由的情况下。
【解决方案2】:

如果您至少使用 C++17,则可以使用来自 #include <charconv>std::to_chars()

// `512` is here arbitrary, it is the max size of the output string. 
// Smaller values should be sufficient.
char buffer[512];
// Here 'std::chars_format::fixed' tells the `std::to_chars()` to 
// not use the scientific notation.
char* end = std::to_chars(std::begin(buffer), std::end(buffer), myDouble, std::chars_format::fixed).ptr;
// `end` the one-past-the-end pointer of the characters written to `buffer`.

此方法可能比 Emilien Lemaire 的答案更快,但它更冗长且更容易出错。所以这个答案只是为了完整性(因为性能提升可能不值得)。

此外,与std::to_string() 不同,输出字符串对语言环境不敏感,因此双精度始终在 C 语言环境(英语语言环境)中格式化。

【讨论】:

  • 不幸的是,我的课程将我们限制在 c++98 范围内,以便让我们了解更基本的 c++ 原理。我尝试过 to_string() 但这也将其缩减为符号。
  • 那么你可以使用std::sprintf(myBuffer, "%f", myDouble)(在C++98中可用)。 %f 格式指定使用十进制表示法。请参阅en.cppreference.com/w/cpp/io/c/fprintf 了解更多详情。
猜你喜欢
  • 2014-06-20
  • 2014-09-19
  • 2017-10-06
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
相关资源
最近更新 更多