2

This string operation prints out a double in short-hand, and I can't work out why. Why is this happening, and how can I get the full output like the first line of output?

string myString = "The value is ";
ss.str(""); // stringstream from ealier
ss.clear();
ss << myDouble; // Double with value 0.000014577
myString.append(ss.str());
cout << myDouble << endl;
cout << myString << endl;

$ ./myapp
0.000014577
The value is 1.4577e-05
jwbensley
  • 10,534
  • 19
  • 75
  • 93
  • 1
    This happens because the precision settings of `cout` and `ss` are different. – Sergey Kalinichenko May 15 '12 at 20:54
  • Thanks to everyone for being so prompt with their answers, I new I was missing something obvious. Thank you all :) – jwbensley May 16 '12 at 08:11
  • If you are using stringstream only for the conversion, [std::to_string](http://en.cppreference.com/w/cpp/string/basic_string/to_string) is also useful. –  May 16 '12 at 15:56

3 Answers3

2

That is because this is the default formatting, you can override it with precision.

zeller
  • 4,904
  • 2
  • 22
  • 40
2

its default behaviour you should use precision to use fixed precision

#include <string>
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
double v = 0.000014577;
cout << fixed << v << endl;
}
Bartosz Przybylski
  • 1,628
  • 10
  • 15
2

Try this:

using std::fixed;
...
ss.setf(fixed);
ss << myDouble;
...
Samy Arous
  • 6,794
  • 13
  • 20