string to double

I would like to convert the string without losing the decimal part and obtainig the same accuracy...

this is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "stdafx.h"

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace std;

int _tmain(int argc, char* argv[]){

string param = "1.65"; 
double L3;

L3=atof(param.c_str());
 
}


If I use atoi L3 = 1.00000; and if I use atof L3 = 1.6499999999; Any idea??

Thank you!!
You need to understand how decimals on a computer are stored to answer this question.
http://stackoverflow.com/questions/14972107/how-does-a-computer-store-decimal-point-values
Specifically maybe read up on the IEEE 754-1985 and the standard that superseded it IEEE 754-2008. Those documents describe how most modern computers deal with floating point numbers.

In short, computers can not represent every value exactly.
Last edited on
Might just be your compiler, but this displays correctly on ideone:
http://ideone.com/WP8Hyx

Alternatively, you can use iomanip to specify the precision:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;

int main() {
	char decimal[] = {"1.65"};
	double L = atof(decimal);
	cout << setprecision(3) << atof(decimal) << " " << L << endl;
	return 0;
}
The problem isn't with the conversion from string to double. If you put
double L3 = 1.65; the result is the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
	string param = "1.65"; 
	double L3;
	
	L3 = atof(param.c_str());
	
	double a = 1.65;
	
	cout.precision(16);
	cout << fixed;
	
	cout << "L3 = " << L3 << endl;
	cout << "a  = " << a  << endl;
	cout << "L3 - a = " << L3 - a << endl;
L3 = 1.6499999999999999
a  = 1.6499999999999999
L3 - a = 0.0000000000000000

Topic archived. No new replies allowed.