fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <limits>
  4. #include <math.h>
  5. using namespace std;
  6.  
  7. void test(double value)
  8. {
  9. int digits_before = 1 + (int)floor(log10(fabs(value)));
  10. int digits_after = std::numeric_limits<double>::digits10 - digits_before;
  11. double whole = floor(pow(10, digits_after) * fabs(value) + 0.5);
  12. while (digits_after > 0 && (whole/10.0 - floor(whole/10.0)) < 0.05)
  13. {
  14. --digits_after;
  15. whole = floor(whole / 10.0 + 0.5);
  16. }
  17. if (digits_after < 0) digits_after = 0;
  18. cout << std::fixed << std::setprecision(digits_after) << value << endl;
  19. }
  20.  
  21. int main() {
  22. test(3.14);
  23. test(3.14159);
  24. test(1000);
  25. test(1000.00000000001);
  26. test(0.00001);
  27. return 0;
  28. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
3.14
3.14159
1000
1000.00000000001
0.00001