在 c++ 中从双精度转换为字符串

Conversion from double to string in c++

本文关键字:转换 字符串 双精度 c++      更新时间:2023-10-16

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

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

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

我会使用:

std::to_string(myDouble);

如果您至少使用 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 语言环境(英语区域设置(格式化。