Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) DoubleToStr

 

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:

 

 

 

 

 

 

C++98STL 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.

 

 

 

 

 

C++98Boost 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);
}

 

 

 

 

 

C++11STL 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);
}

 

 

 

 

 

External links

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict