Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Today I tried out some new functions of the C++11 STL and encountered std::to_string.

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;

The result?

0.330000

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.

Anyone encountered this problem before/has a solution? Some StackOverflow searches yielded nothing.

(A C++11 STL reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
852 views
Welcome To Ask or Share your Answers For Others

1 Answer

If all you want to do is remove trailing zeros, well, that's easy.

std::string str = std::to_string (f);
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...