1. std:to_string()方法只能精确到6位小数点
double d = 3.1415926535897932384;
string str = std::to_string(d);
cout << str << std::endl; // 3.141593
2. 使用stringstream,在输入流时使用setprecision设置精度,需包含头文件 <iomanip>
std::stringstream ss;
ss << setprecision(15) << d;
str = ss.str(); // 3.14159265358979
3. 完整测试代码:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
double d = 3.1415926535897932384;
string str = std::to_string(d);
cout << str << std::endl; // 3.141593
std::stringstream ss;
ss << setprecision(15) << d;
str = ss.str();
cout << str << std::endl; // 3.14159265358979
return 0;
}
输出:
注意:对于double类型,setprecision(15) 参数最大有效值为15,超过15,数据就不保证可靠了。