fork(3) download
  1. #include <cmath>
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <limits>
  5. #include <sstream>
  6.  
  7. std::string make_string(double x, int precision)
  8. {
  9. std::ostringstream output;
  10. output << std::setprecision(precision) << x;
  11. return output.str();
  12. }
  13.  
  14. int digits_before_point(double x)
  15. {
  16. return x ? int(floor(std::log(std::abs(x)) / std::log(10.0) + 1)) : 0;
  17. }
  18.  
  19. std::string format(double x, int precision = 2)
  20. {
  21. const auto dbp = digits_before_point(x);
  22. if (dbp + precision > 0)
  23. {
  24. return make_string(x, dbp + precision);
  25. }
  26. else if (dbp + precision == 0)
  27. {
  28. const double min_value = std::exp(-precision * std::log(10));
  29. if (x >= min_value / 2)
  30. {
  31. return make_string(min_value, 1);
  32. }
  33. else if(x <= -min_value / 2)
  34. {
  35. return make_string(-min_value, 1);
  36. }
  37. }
  38. return "0";
  39. }
  40.  
  41. int main()
  42. {
  43. std::cout << format(-123456.949) << std::endl;
  44. std::cout << format(-123456.004) << std::endl;
  45. std::cout << format(-123456.005) << std::endl;
  46. std::cout << format(-123456.) << std::endl;
  47. std::cout << format(0) << std::endl;
  48. std::cout << format(0.9499) << std::endl;
  49. std::cout << format(0.0049999) << std::endl;
  50. std::cout << format(0.005) << std::endl;
  51. }
Success #stdin #stdout 0s 4564KB
stdin
Standard input is empty
stdout
-123456.95
-123456
-123456.01
-123456
0
0.95
0
0.01