C++ double 转string 精度保持到小数点后15位

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,数据就不保证可靠了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值