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

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

c++ - C++11 std::to_string(double) - No trailing zeros

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

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

1 Answer

0 votes
by (71.8m points)

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...