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

来源:互联网 发布:初学者吉他知乎 编辑:程序博客网 时间:2024/06/08 18:46

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


0 0