[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppDoubleToStr

(C++) Converting a double to a std::string

When not using the Boost C++ Library

In analogy with the standard 'atof' function, doing the other way around:

(function taken from from Marshall Cline's C++ FAQ Lite document http://www.parashift.com/c++-faq-lite/)

  1. include <sstream>
  2. include <cassert>
std::string ftoa(const double& x) { std::ostringstream o; if (!(o << x)) return "ERROR"; return o.str(); } int main() { assert(ftoa("69.69")==69.69); }


You could also use the Boost C++ Library's lexical_cast:

  1. include <cassert>
  2. include <string>
  3. include <boost/lexical_cast.hpp>
int main() { const double d = 123.456; const std::string s = boost::lexical_cast<std::string>(d); assert(s == "123.456"); }


Other code snippets

Topic links



last edited (November 4, 2006) by bilderbikkel, Number of views: 6112, Current Rev: 11 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.