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