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
source share