//file name: ToRMB.h
//complied ok with vc++6.0
#include <string>
#include <stdio.h>
#include <iostream>
#include <vector>
using std::vector;
using std::string;
using std::cout;
using std::cin;
using std::endl;
string NumberToRMB(double dNum){
string strResult;//要返回的字符串
char c_Digit[20];//c风格的字符数组
string strDigit;//输入的数字字符串
int iLength = 0;//输入的双精度数的长度
int iAddZero = 0;//加零标志
int iDigit = 0;//取出的数字
string str1[] = {"分","角","元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟","万","拾","佰","仟"};
string str2[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
vector<string> strUnit(str1,str1 + 18);//初始化向量
vector<string> strUpperNum(str2,str2 + 10);
sprintf(c_Digit,"%.0f",dNum*100);//将数字串换成c风格的数组
strDigit = c_Digit;//将字符数组的内容赋值给string变量
iLength = strDigit.length();//取得字符串的长度
//如果输入的数字超出double类型数据的长度的话返回“error“
if (iLength > 15 || iLength < 0) return "Error";
for (int i = 0; i < iLength; i++) {//将字符串逐位处理
iDigit = atoi(strDigit.substr(i,1).c_str());
if (iDigit == 0)//如果当前位为零,则将加零标志+1
iAddZero++;
else
{
if (iAddZero > 0)//如果当前为不为0,且加0标志大于0
strResult += "零";//则在字符串中加入“零“
strResult += strUpperNum[iDigit];
iAddZero = 0;
}
//该位不为0||元位||亿位||万位
if ((iDigit != 0) || (iLength - i == 3) || (iLength - i == 11)||((iLength - i + 1)%8 == 0 && (iAddZero < 4)))
strResult += strUnit[iLength - i - 1];
}
if (strDigit.substr(strDigit.length() - 2,2) == "00")
//strResult += "??";
strResult += "";
return strResult;
}
//demo.cpp
#include "ToRMB.h"
using namespace std;
int main()
{
double dLowerRMB = 0.0;
cout << "请输入人民币金额!" << endl;
cin >> dLowerRMB;
cout << "小写金额= " <<dLowerRMB << endl;
string toRMB = NumberToRMB(dLowerRMB);
cout << "大写金额= " <<toRMB<< endl;
cout << "-------------------------------------------------" << endl;
return 0;
}
数字到大写金额的转换C++
最新推荐文章于 2022-05-14 16:00:55 发布