转换用于计算的时候数据的精度容易出现问题,常见的是转换为double型之后112.0707922变成 112.07079219999999964;
除此之外还有就是输出精度问题,这块其实还不是很明白,我现在的理解是double在程序中的位数是固定的,计算过程中的小数位数是固定的;可控制的是输出的精度,而非参与运算的精度。
void setLongitude(string longitude){
this->longitude = (double)atof(longitude.c_str());
cout << "got longitude: " << longitude << endl;
cout << "setting longitude: " << this->longitude << endl;
}
结果:
got longitude: -122.39381636393
setting longitude: -122.394
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "-122.39381636393";
std::cout.precision(20);
cout << "setting longitude: " << stod(str) << endl;
return 0;
}
cout << "Setting longitude: " << setprecision(15) << this->longitude << endl;
#include <iostream>
#include <string>
#include <sstream> //for istringstream
#include <iomanip> //for setprecision
#include <cstdio> //for sscanf
using namespace std;
int main()
{
cout << "/************string to double************/" << endl;
/************string to double************/
string str = "12.34567890e2";
cout << "string: "<<str << endl;
//using std::stod
double d;
string::size_type size; //13
d = stod(str, &size); //1234.56789
cout << "double value get by stod: " << setprecision(14) << d << ", size:"<<size << endl; //Note: must setprecision to see entire value
//using sstream
istringstream istrStream(str);
istrStream >> d; //1234.56789
cout << "double value get by istringstream:" << setprecision(14) << d << endl;
//using sscanf
int len; //13
sscanf_s(str.c_str(), "%14lf%n", &d, &len); //1234.56789
cout << "double value get by sscanf: " << setprecision(14) << d <<", size:"<<len<< endl;
cout << "\n\n/**************double to string***************/" << endl;
/**************double to string***************/
double d8 = 1.123456789e2;
cout << "double value: " << setprecision(14) << d8 << endl;
string str8 = std::to_string(d8);//112.345679
cout << "string get by std::to_string: " << str8 << endl;
ostringstream ostrStream;
ostrStream << setprecision(10);
ostrStream << d8;
str8 = ostrStream.str();//112.3456789
cout << "string get by ostringstream: "<< str8 << endl;
char ch[64];
sprintf_s(ch, "%g", d8);
str8 = ch;//112.346
cout << "string get by sprintf: " << str8 << endl;
//below code is used to avoid control exit quickly
char c;
cin >> c;
return 0;
}
参考:https://www.v2ex.com/t/375560