I loose some precision when converting string to float.

Hello,

When I convert a string to float I get a value that is a little smaller. e.g. as in the code below I expect price to be 1.3467800 (which std::cout outputs correctly) but it's actually 1.3467994.

Does someone know what's going? -- THX!

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<string>
#include<sstream>	// stringstream
using namespace std;
double my_stod(std::string& s);

int main()
{
    string str = "1.34678";
    float price = my_stod(str);
    float price2 = atof(str.c_str());
    cout << "price1 = " << price <<
            " price2 = " << price2 << endl << flush;
    return 0;
}

double my_stod(std::string& s)
{
    std::istringstream stream(s);
    double i;
    stream >> i;
    return i;
}
That's the way of the world. Floating point representation isn't exact for all values.
http://en.wikipedia.org/wiki/Floating_point#Machine_precision
Further to kbw's link, this is helpful: http://floating-point-gui.de/

Welcome to the world of computing.
Topic archived. No new replies allowed.