C ++ 11 std :: to_string(double) - 没有尾零 [英] C++11 std::to_string(double) - No trailing zeros

查看:436
本文介绍了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):


返回:每个函数返回一个字符串对象,该对象包含其参数值的字符表示,该参数将通过调用具有格式说明符%d,%u的sprintf(buf,fmt, %ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld / p>

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

以此顺序声明的函数:

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) - 没有尾零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆