逗号部分代码部分参考:如何将数值,金额以逗号分隔
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int unify_money(string& strValue, int unifyType)
{
if(strValue.size() < 1)
return false;
//转化为纯数字
string strNum = "";
for(int i = 0; i < (int)strValue.size(); i++)
{
if(strValue[i] >= '0' && strValue[i] <= '9')
strNum = strNum + strValue[i];
}
//判断正负号
bool positive = true;
if(strValue[0] == '-' || strValue[0] == '_' || strValue[0] == '一')
positive = false;
//进行统一
string strUnify = "";
if(unifyType == 0)
{//添加逗号和小数点
if(strValue.size() < 3)
return false;
if(strNum.size() <= 2)
return false;
strUnify = '.' + strNum.substr(strNum.size() - 2);
strNum = strNum.substr(0, strNum.size() - 2);
int count = (strNum.length() - 1) / 3;
int mod = strNum.size() % 3;
if(mod == 0 && count != 0)
mod = 3;
for(int i = 1; i <= count; i++)
{
strNum.insert(mod + 3*(count - i), ",");
}
strUnify = strNum + strUnify;
strValue = strUnify;
if(positive == false)
strValue = '-' + strValue;
}
else if(unifyType == 1)
{//添加小数点
if(strValue.size() < 3)
return false;
if(strNum.size() < 2)
return false;
strUnify = strNum.substr(0, strNum.size() - 2) + '.' + strNum.substr(strNum.size() - 2);
strValue = strUnify;
if(positive == false)
strValue = '-' + strValue;
}
else if(unifyType == 2)
{//纯数字
strValue = strNum;
if(positive == false)
strValue = '-' + strValue;
}
else if(unifyType == 3)
{//添加逗号
int count = (strNum.length() - 1) / 3;
int mod = strNum.size() % 3;
if(mod == 0 && count != 0)
mod = 3;
for(int i = 1; i <= count; i++)
{
strNum.insert(mod + 3*(count - i), ",");
}
strUnify = strNum + strUnify;
strValue = strUnify;
if(positive == false)
strValue = '-' + strValue;
}
}
int main()
{
for(int i = 0; ; i++)
{
string inputUnifyType = "";
cout << "unifyType = ";
cin >> inputUnifyType;
cin.sync();
cout << endl;
if(inputUnifyType == "break")
break;
int unifyType = stoi(inputUnifyType);
string inputStr = "";
for(int j = 0; ; j++)
{
cout << "inputStr = ";
cin >> inputStr;
cin.sync();
cout << endl;
if(inputStr == "break")
break;
unify_money(inputStr, unifyType);
cout << "unifyStr = " << inputStr <<endl;
cout << endl;
}
}
}