Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant solution to remove trailing 0's with precision set

Tags:

c++

std

boost

c++14

Is there any elegant solution using the std C++ or Boost libraries to output a double to std::cout in a way that the following conditions are met:

  1. scientific notation is disabled
  2. the precision for the decimal part is 6
  3. however, trailing 0's (for the decimal part) are not printed out

For example:

double d = 200000779998;
std::cout << `[something]` << d;

should print out exactly 200000779998. [something] should possibly be a noexcept combination of some existing manipulators.

This is not a solution to the problem:

std::cout << std::setprecision(6) << std::fixed << d;

because it prints out 200000779998.000000 with trailing 0's

like image 763
Martin Avatar asked Nov 19 '22 02:11

Martin


1 Answers

Instead of using the fixed manipulator, you can try to use (abuse?) defaultfloat. As far as I understand, it chooses either fixed or scientific based on the ability to put the number within the specified precision. As a result you can set the precision to the number of digits of the integral part + the requested fractional precision (6 in your case).

double d = 200000779998;
std::cout << std::setprecision(integralDigits(d) + 6) << d << std::endl;

You can try it here.

like image 185
yenj Avatar answered Dec 19 '22 17:12

yenj