在c ++中从双精度转换为字符串[重复]

Posted

技术标签:

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

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

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

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

【问题讨论】:

这能回答你的问题吗? Double to string conversion without scientific notation 不是 C# 问题,@UtkarshGupta 这能回答你的问题吗? Turn off scientific notation on float 或者这个:***.com/questions/6301547/… 【参考方案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 了解更多详情。

以上是关于在c ++中从双精度转换为字符串[重复]的主要内容,如果未能解决你的问题,请参考以下文章

在 C 中从 HEX 颜色转换为 RGB 结构

在sql中从字符串转换为日期时间[重复]

在 C/C+ 中从 16 位线性 PCM 音频转换为 32 位浮点的最佳方法?

如何在目标 c 中从 int 转换为字符串:示例代码

在Java中从整数转换为二进制时保留整个字节[重复]

如何将多个重复行转换为列,然后在记事本++中从列转换回行