标准化金额:加小数点和逗号 / 加逗号 / 加小数点 / 纯数字

逗号部分代码部分参考:如何将数值,金额以逗号分隔

#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;
		}
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值