fork(5) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. using namespace std;
  5.  
  6. std::string doubleToString(double f, int p)
  7. {
  8. std::stringstream ss;
  9. int p2 = min(p + 2, 14);
  10. ss << std::fixed << std::setprecision(p2) << f;
  11. std::string s = ss.str();
  12. size_t point = s.find('.');
  13. if (point != std::string::npos && point + 1 + p < s.size())
  14. s.erase(point + 1 + p);
  15. s.erase(s.find_last_not_of('0') + 1, std::string::npos);
  16. return (s[s.size()-1] == '.') ? s.substr(0, s.size()-1) : s;
  17. }
  18.  
  19. int main() {
  20. double test1 = 1;
  21. double test2 = 1.12345678;
  22. double test3 = 1.123456789010;
  23.  
  24. std::cout << doubleToString(test1, 8) << " " << doubleToString(test2, 8) << " " << doubleToString(test3, 8);
  25. return 0;
  26. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
1 1.12345678 1.12345678