Losing precision in string to double conversion

Hello, I have a problem with string to int, atof() to be precise. It doesn't happen every time, but sometimes it rounds up numbers.

Here is the problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string a, b, c;
a = "23145.23"
b = "254687.54"
c = "235461.78"

double x, y, z;
x = atof(a.c_str());
y = atof(b.c_str());
z = atof(c.c_str());

cout << a << "\t" << b << "\t" << c << endl;
cout << x << "\t" << y << "\t" << z << endl;

//OUTPUT
//23145.23    254687.54   235461.78
//23145.2   254688   235462

//values that get converted properly: 1.25646   1.23654   2.45624 


Anyone have any idea how to stop this from happening?
Last edited on
It's printing 6 significant figures, which I believe is the default. The other figures are there, you just aren't printing them. Use precision() or setprecision() to set it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdlib>

using std::atof;
using std::cout;
using std::endl;

int main()
{
    const char *a = "23145.23",
        *b = "254687.54",
        *c = "235461.78";

    double x, y, z;
    x = atof(a);
    y = atof(b);
    z = atof(c);

    cout << a << "\t" << b << "\t" << c << endl;
    cout << x << "\t" << y << "\t" << z << endl;
    cout.precision(10);
    cout << x << "\t" << y << "\t" << z << endl;
}

23145.23        254687.54       235461.78
23145.2 254688  235462
23145.23        254687.54       235461.78

Of course. I don't know how I could have missed it. Thank you DHayden!
Topic archived. No new replies allowed.