Difference between revisions of "Talk:cpp/string/basic string/to string"
From cppreference.com
(Created page with "==== Not round-trip safe. ==== Please mention that {{lc|std::to_string}} is not round-trip-safe for floating point numbers. Please mention "not round-trip-safe" explaining th...") |
|||
Line 22: | Line 22: | ||
const std::string sNum = oss.str(); | const std::string sNum = oss.str(); | ||
const std::string sNumBad = std::to_string(x); | const std::string sNumBad = std::to_string(x); | ||
− | std::cout << "sNum == " << sNum << " (round-trip-safe!)\n"; | + | std::cout << "sNum == " << sNum << " (round-trip-safe!)\n"; |
− | std::cout << "sNumBad == " << | + | std::cout << "sNumBad == " << << '\n'; |
double y; | double y; |
Revision as of 09:45, 26 July 2023
Not round-trip safe.
Please mention that std::to_string is not round-trip-safe for floating point numbers. Please mention "not round-trip-safe" explaining that converting a double to a std::string and then back to a double will not yield the same number in every case.
Please provide an example of how to perform a round-trip-safe conversion, e.g. maybe something similar to this:
Run this code
#include <iostream> #include <iomanip> #include <string> #include <limits> #include <sstream> #include <cassert> int main() { double x = 3.33333333333333333333333333; std::ostringstream oss; oss << std::setprecision(std::numeric_limits<decltype(x)>::max_digits10) << x; const std::string sNum = oss.str(); const std::string sNumBad = std::to_string(x); std::cout << "sNum == " << sNum << " (round-trip-safe!)\n"; std::cout << "sNumBad == " << sNumBad << '\n'; double y; double yBad; std::istringstream(sNum) >> y; std::istringstream(sNumBad) >> yBad; std::cout << "(x == y ) is " << std::boolalpha << (x==y) << '\n'; std::cout << "(x == yBad) is " << std::boolalpha << (x==yBad) << '\n'; }