fork(3) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <cmath>
  5.  
  6. size_t digits_before_point(double x)
  7. {
  8. return x ? size_t(std::max(0.0, floor(std::log(std::abs(x)) / std::log(10.0) + 1))) : 0;
  9. }
  10.  
  11. std::string format(double x, size_t precision = 2)
  12. {
  13. std::ostringstream output;
  14. output << std::setprecision(digits_before_point(x) + precision) << x;
  15. return output.str();
  16. }
  17.  
  18. int main()
  19. {
  20. std::cout << format(-123456.949) << std::endl;
  21. std::cout << format(-123456.004) << std::endl;
  22. std::cout << format(-123456.005) << std::endl;
  23. std::cout << format(-123456.) << std::endl;
  24. std::cout << format(0) << std::endl;
  25. std::cout << format(0.9499) << std::endl;
  26. }
Success #stdin #stdout 0s 4368KB
stdin
Standard input is empty
stdout
-123456.95
-123456
-123456.01
-123456
0
0.95