string与doule互相转换并保留两位小数

4 篇文章 0 订阅

其实string与double、int的互转有一些函数可以直接用,例如:

	//doule转string 
	string str1 = to_string(3.14);
	//int转string
	string str2 = to_string(4);
	//string转int
	int x= atoi(str2.c_str());
	//string转double
	double y = stof(str1.c_str());

但是不满足我想顺便四舍五入保留小数位的需求,所以自己写了两个函数。

用模板实现的,可以兼容int 和double的类型,但实际上int不用保留小数位,这个可以再改进一下,main函数内是测试的例子。

#include <iostream>
#include <string>
#include<sstream>
#include <iomanip>
#include <cmath>
using namespace std;

template<typename T>
string ToString(T val)//doule转string
{
	stringstream ss;
	ss << setiosflags(ios::fixed) << setprecision(2) << val;//保留两位小数
	string str = ss.str();
	return str;
}
template<typename T>
T ToDouble(string input)//string转double
{
	T result;
	stringstream ss;
	ss << input;
	ss >>result;
	result = round(result * 100)/ 100;//四舍五入保留两位小数
	return result;
}

int main()
{
	//测试
	string sa = "2.5686";
	double a = ToDouble<double>(sa);
	cout << a << endl;

	double b = 3.256454;
	string sb = ToString(b);
	cout << sb << endl;

	string sc = "4.002";
	int c = ToDouble<int>(sc);
	cout << c << endl;

	int d = 5;
	string sd = ToString(d);
	cout << sd << endl;

// 	//doule转string 
// 	string str1 = to_string(3.14);
// 	//int转string
// 	string str2 = to_string(4);
// 	//string转int
// 	int x= atoi(str2.c_str());
// 	//string转double
// 	double y = stof(str1.c_str());

	system("pause");
	return 0;
}

运行结果:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值