Changeset 1001 for cpp/common
- Timestamp:
- 07/14/20 00:21:40 (4 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
cpp/common/nonstd_math.cpp
r980 r1001 15 15 } 16 16 17 std::string doubleToString(double x, int precision) 17 18 std::string doubleToString(double x, int precision) //waiting for a proper, native C++ solution 18 19 { 19 std::stringstream ss; 20 ss << std::fixed; 21 ss.precision(precision); //set the number of places after decimal 22 ss << x; 23 return ss.str(); 20 std::stringstream ss; //or for pre-allocated buffer, sprintf(s, "%.*f", precision, x); 21 std::string str; 22 if (fabs(x) < 1e8) //limiting the precision of huge fp values makes little sense - better use scientific notation, unless we want a looong number 23 { 24 ss << std::fixed; 25 ss.precision(precision); //set the number of places after decimal 26 ss << x; 27 str = ss.str(); 28 char *s = str.data(); //now we will be operating directly on the internal std::string buffer 29 for (int i = str.length() - 1, end = str.length(); i >= 0; i--) //remove trailing zeros, and maybe also '.' 30 { 31 if (s[i] == '0') 32 { 33 if (end == i + 1) 34 end = i; 35 } 36 else if (s[i] == '.') 37 { 38 if (end == i + 1) 39 end = i; 40 s[end] = '\0'; 41 break; 42 } 43 } 44 } 45 else 46 { 47 ss << x; 48 str = ss.str(); 49 } 50 //printf("%.17g and %d decimals: %s\n", x, precision, str.c_str()); 51 return str; 24 52 } 25 53
Note: See TracChangeset
for help on using the changeset viewer.