DoubleToStr is a code snippet to convert an double to std::string. To convert a std::string to double, use StrToDouble.
DoubleToStr has multiple versions:
- DoubleToStr using the C++98 and the STL
- DoubleToStr using the C++98 and the Boost library
- DoubleToStr using the C++11 and the STL
DoubleToStr using the C++98 and the STL
#include <stdexcept> #include <sstream> //From http://www.richelbilderbeek.nl/CppDoubleToStr.htm const std::string DoubleToStr(const double x) { std::ostringstream s; if (!(s << x)) throw std::logic_error("DoubleToStr failed"); return s.str(); }
The code snippet above was modified from the C++ FAQ Lite.
DoubleToStr using the C++98 and the Boost library
#include <string> #include <boost/lexical_cast.hpp> //From http://www.richelbilderbeek.nl/CppDoubleToStr.htm const std::string DoubleToStr(const double x) { return boost::lexical_cast<std::string>(x); }
DoubleToStr using the C++11 and the STL
#include <string> //From http://www.richelbilderbeek.nl/CppDoubleToStr.htm const std::string DoubleToStr(const double x) { return std::to_string(x); }