Convert double to string with fixed point, no trailing zeros and witout sprintf

This question has been asked a couple of times, but all answers either relate to sprintf, or include removing trailing zeros manually. Is there really no better way? Is this impossible to achieve with std::stringstream ?

+1
source share
2 answers

First, you will calculate how many potential digits you have before and after the decimal:

 int digits_before = 1 + (int)floor(log10(fabs(value))); int digits_after = std::numeric_limits<double>::digits10 - digits_before; 

Then you will find out how many of these numbers are zeros:

 double whole = floor(pow(10, digits_after) * fabs(value) + 0.5); while (digits_after > 0 && (whole/10.0 - floor(whole/10.0)) < 0.05) { --digits_after; whole = floor(whole / 10.0 + 0.5); } if (digits_after < 0) digits_after = 0; 

Now you have a value that you can use with std::setprecision :

 std::stringstream ss; ss << std::fixed << std::setprecision(digits_after) << value; 

Ultimately, this is a lot of work and duplicates the efforts that string conversion does anyway, so people usually just convert to a string and remove trailing zeros. And no, there is no easy formatting option to do this, you need to do it hard or not.

See the above code in action: http://ideone.com/HAk55Y

+4
source

If the goal is to have a fixed point x or less for trailing zeros, throw a double through a fixed sstream. Then cut off the rest with an unfixed exit.

 double number = 1.03000; std::stringstream s.precision(6); s << number; std::cout << s.str(); 

Edit: To save the results

 std::string result = s.str(); 
-1
source

All Articles