C++11 std::to_string(double) - No trailing zeros(C++11 std::to_string(double) - 没有尾随零)
问题描述
今天尝试了C++11 STL的一些新函数,遇到了std::to_string
.
Today I tried out some new functions of the C++11 STL and encountered std::to_string
.
可爱、可爱的功能集.为一个双字符到字符串的转换创建一个 stringstream 对象对我来说总是显得有些矫枉过正,所以我很高兴我们现在可以做这样的事情:
Lovely, lovely set of functions. Creating a stringstream object for just one double-to-string conversion always seemed overkill to me, so I'm glad we can now do something like this:
std::cout << std::to_string(0.33) << std::endl;
结果?
0.330000
我对此并不完全满意.有没有办法告诉 std::to_string
去掉尾随的零?我在互联网上搜索过,但据我所知,该函数只接受一个参数(要转换的值).回到使用 stringstreams 的过去",您可以设置流的宽度,但我不想转换回来.
I'm not entirely content with that. Is there a way to tell std::to_string
to leave out the trailing zeros? I searched the internet, but as far as I can see the function takes only one argument (the value to be converted). Back in 'the old days' with stringstreams, you could set the width of the stream, but I'd rather not convert back.
有人遇到过这个问题/有解决方案吗?一些 StackOverflow 搜索没有结果.
Anyone encountered this problem before/has a solution? Some StackOverflow searches yielded nothing.
(C++11 STL 参考:http://en.cppreference.com/w/cpp/string/basic_string/to_string)
(A C++11 STL reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string)
推荐答案
C++11 标准明确规定 (21.5/7
):
The C++11 Standard explicitely says (21.5/7
):
返回:每个函数返回一个字符串对象,其中包含其参数值的字符表示,该值将通过调用 sprintf(buf, fmt, val) 生成,格式说明符为%d"、%u",分别为 "%ld"、"%lu"、"%lld"、"%llu"、"%f"、"%f" 或 "%Lf",其中 buf 指定足够大小的内部字符缓冲区>
Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, where buf designates an internal character buffer of sufficient size
对于按此顺序声明的函数:
for the functions declared in this order:
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
因此,您无法控制结果字符串的格式.
Thus, you cannot control the formatting of the resulting string.
这篇关于C++11 std::to_string(double) - 没有尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++11 std::to_string(double) - 没有尾随零
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01