将任意的整数,浮点数转换为字符串(自己摸索的,也许有错误。建议还是使用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;
}