c++任意数字转换为字符串

将任意的整数,浮点数转换为字符串(自己摸索的,也许有错误。建议还是使用boost库

lexical_cast

template<typename T>
string ConvertAnyNumToString(T iValue)
{
	string outPutStr, tmp;
	//1.判断正负,取正数
	if (iValue < 0)
	{
		outPutStr.push_back('-');
		iValue = -iValue;
	}

	//2.判断是int/long 还是double/float;
	//如果为double/float,就将整数和小数部分,分开转换
	long long int lValue = iValue; //整数
	float dDecimal = iValue - lValue;//小数
	
	//3.整数部分转换
	while (lValue > 0)
	{
		int remainValue = lValue % 10;
		tmp.push_back('0' + remainValue);//ascii码
		lValue = lValue / 10;
	}
	for (int iIndex = 0; iIndex < tmp.length(); iIndex++)
	{
		outPutStr.push_back(tmp[tmp.length() - 1 - iIndex]);//添加原本逆序的整数部分
	}


	//4.小数部分转换
	
	if (dDecimal > 0)
	{

		//计算小数位数
		int nDecimalLen = 0;
		long long int lliValue = iValue;
		double dVal1 = iValue,tmp2;
		while ((dVal1 - (double)lliValue) > 0)
		{
			dVal1 = iValue * pow(10,nDecimalLen + 1);
			lliValue = dVal1;
			
			nDecimalLen++;
			tmp2 = dVal1 - (double)lliValue;
		}
		outPutStr.push_back('.'); //添加小数点
		while (nDecimalLen  > 0)
		{
			dDecimal *= 10;
			outPutStr.push_back('0' + (int)dDecimal);
			dDecimal = dDecimal - (int)dDecimal;
			nDecimalLen--;
		}
	}

	//5.组合最终结果,并返回字符串
	return outPutStr;
}
 
int _tmain(int argc, _TCHAR* argv[])
{
	double dVal = -12.123456789;
	cout << ConvertAnyNumToString(dVal) << endl;

	//float fVal = -12.1234;
	cout << ConvertAnyNumToString(-12.1234) << endl;

	long lVal = 12345678;
	cout << ConvertAnyNumToString(lVal) << endl;

	int iVal = 123456;
	cout << ConvertAnyNumToString(iVal) << endl;

	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值