10

I am having some issues trying to convert a double to C++ string. Here is my code

std::string doubleToString(double val)
{
    std::ostringstream out;
    out << val;
    return out.str();
}

The problem I have is if a double is being passed in as '10000000'. Then the string value being returned is 1e+007

How can i get the string value as "10000000"

  • 12
    How about some of the examples from the following: http://www.codeproject.com/KB/recipes/Tokenizer.aspx They are very efficient and somewhat elegant. –  Nov 02 '10 at 05:04

3 Answers3

14
#include <iomanip>
using namespace std;
// ...
out << fixed << val;
// ...

You might also consider using setprecision to set the number of decimal digits:

out << fixed << setprecision(2) << val;
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
8
#include <iomanip>

std::string doubleToString(double val)
{
   std::ostringstream out;
   out << std::fixed << val;
   return out.str();
}
scunliffe
  • 62,582
  • 25
  • 126
  • 161
workmad3
  • 25,101
  • 4
  • 35
  • 56
2

You can also set the minimum width and fill char with STL IO manipulators, like:

out.width( 9 );
out.fill( ' ' );
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171