0

I have a string with the value 788597.31 and I am converting this value to double but when I print the variable only 788597 is displayed. I have used std::stod(string) and even stringstream but everytime I get the same previous value. Can anybody help me with this? I want to store this string value in a double varaible.

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
  string s="788597.31";
  double d=stod(s);
  cout<<d<<" ";
  stringstream g;
  double a; 
  g<<s; g>>a;
  cout<<a;

  return 0;
}
Sarthak
  • 1
  • 1

1 Answers1

0

The problem is in how you are printing your result, not in the string parsing. This program:

#include <iostream>
using namespace std;

int main() {
    cout << 788597.31 << endl;
    return 0;
}

also prints 788597.

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    cout << setprecision(10) << 788597.31 << endl;
    return 0;
}

prints 788597.31

If you want to see more than the default 6 significant digits your program needs to say so.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75