在 c++ 中从双精度转换为字符串
Conversion from double to string in c++
我目前正在为我的计算机科学模块编写一个项目,但如果双精度值中的小数位太多,我的字符串值默认为科学记数法,我遇到了问题。
我已经尝试了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 语言环境(英语区域设置(格式化。
相关文章:
- wcstombs_s(),转换字符串的长度
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 无法转换字符串插入函数的参数
- 转换字符串向量:基于先前的值跳过元素
- 从中间器转换字符串不起作用,出了什么问题?
- 失败的证明转换字符串到枚举类
- 如何使用正则表达式和提升转换迭代器标记和转换 c 字符串
- 使用java jni时转换字符串类型
- 如何避免在转换字符串令牌流时重复istringstream构造
- 阿托伊未正确转换字符串
- C++,转换字符串,使连续下划线序列变为单个下划线
- 使用长算术转换字符串
- 转换字符串十进制数时的精度
- 将词法转换字符串提升为双精度
- 使用marshal_as函数转换字符串的性能
- C++不会从数据转换字符串
- 无论如何,在c++ /Qt中转换字符串到结构中的字段
- C++ 隐式类型转换字符串 -> int?
- 转换字符串到浮点数,c++实现
- 用于转换字符串大小写的函数