1

I have a small problem with stringstream. It loses precision when I use it to convert string to double.

const std::string str = "44.23331002";
double x;
stringstream ss;
ss << str;
ss >> x;
cout << str << " = " << x << endl;

The output is: 44.23331002 = 44.2333

Why is this? Does it convert to float and has limited digit precision?

  • You take a tiny rounding error when converting from string to double, but the real issue is how you're converting from double to string. – user2357112 Dec 04 '15 at 18:23
  • well, floating point is not the most precise thing ever. if you must have the presicion, parse it yourself with a simple loop. even then, small precision bugs may occur – David Haim Dec 04 '15 at 18:24
  • Look at std::setprecision and std::ios_base::precision –  Dec 04 '15 at 18:25

2 Answers2

5

You need to set the precision on the output stream:

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

int main() {
    const std::string str = "44.23331002";
    double x;
    stringstream ss;
    ss << str;
    ss >> x;
    cout << str << " = " << std::setprecision(10) << x << endl;
}

Output:

44.23331002 = 44.23331002

(Demo)

clcto
  • 9,530
  • 20
  • 42
  • 1
    Ahh, so the problem is on the cout's side. I thought the converting fails here. – This is temp display name Dec 04 '15 at 18:30
  • @Grzyboo - the problem is in the round-trip conversion to text and back; the outgoing conversion has six digits of precision, so that's all that's present in the incoming conversion. Neither conversion is wrong, but the combination doesn't do what's needed. – Pete Becker Dec 04 '15 at 19:08
1

calcto answered correctly.and You can change precision in two way: std::setprecision(10) and std::cout.precision(10)