fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <string>
  5. #include <cassert>
  6.  
  7. std::string format(double x, int precision = 2)
  8. {
  9. std::ostringstream output;
  10. output << std::fixed << std::setprecision(precision) << x;
  11. std::string s = output.str();
  12.  
  13. if (precision > 0)
  14. {
  15. const auto pos = s.find_last_not_of('0');
  16. assert(pos != std::string::npos);
  17.  
  18. if (pos != s.size() - 1)
  19. {
  20. const auto count = s[pos] != '.' ? pos + 1 : pos;
  21. return s.substr(0, count);
  22. }
  23. }
  24. return s;
  25. }
  26.  
  27. int main()
  28. {
  29. std::cout << format(0) << std::endl;
  30. std::cout << format(1e-20) << std::endl;
  31. std::cout << format(1e+20) << std::endl;
  32. std::cout << format(123456.0049999) << std::endl;
  33. std::cout << format(123456.005) << std::endl;
  34. std::cout << format(123456.695) << std::endl;
  35. std::cout << format(0x1.6bcc41e8ffffap+46) << std::endl;
  36. }
Success #stdin #stdout 0s 4528KB
stdin
Standard input is empty
stdout
0
0
100000000000000000000
123456
123456.01
123456.7
99999999999999.91