将一个千亿之内的数转换成中文,可以包含小数
思路:对于存在小数的情况下,拆分出来整数部分和小数部分。
关键是整数部分。以4位分隔作为一小节
对于节内的转换处理
0时,是不输出单位的
连续0时只输出一个
对于节间的处理
如果当前节小于1000,并且前面还存在节时,需要补上0
当前节等于0时,不输出
代码如下:
class NumToChinese
{
public:
string convert(const string& strNum)
{
int num = 0;
string:size_t pos = strNum.find(".");
if (pos != string::npos) {
num = stoi(strNum.substr(0, pos));
} else {
num = stoi(strNum);
}
string ans;
bool needZero = false;
int curPos = 0;
while (num > 0) {
int section = num % 10000;
if (needZero) {
ans.insert(0, numChars[0]);
}
string sectionStr = convertSection(section);
if (section) {
sectionStr += bigUnits[curPos];
}
ans.insert(0, sectionStr);
needZero = (section > 0 && section < 1000);
num /= 10000;
++curPos;
}
if (pos != string::npos) {
ans.append("点");
for (size_t i = pos + 1; i < strNum.size(); i++) {
ans.append(numChars[strNum[i] - '0']);
}
}
return ans;
}
private:
string convertSection(int num)
{
string ans;
bool zero = true;
int pos = 0;
while (num > 0) {
int cur = num % 10;
if (cur == 0) {
if (!zero) {
zero = true;
ans.insert(0, numChars[cur]);
}
} else {
zero = false;
string tmp = numChars[cur];
tmp += units[pos];
ans.insert(0, tmp);
}
num /= 10;
++pos;
}
return ans;
}
vector<string> units{"", "十", "百", "千"};
vector<string> bigUnits{"", "万", "亿"};
vector<string> numChars{"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
};