Qt 中 qint64 转 汉字写法
如 9223372036854775807
转为 九百二十二兆三千三百七十二亿零三百六十八万五千四百七十七万五千八百零七
注意:此过程并未检查 qint64 类型的的上限!!
使用的是中国传统的乘方数位,即“一百个一百为一万,一万个一万是一亿,一亿个一亿是一兆”,即可有如下数位:
个,十,百,千,万,十万,百万,千万,亿,十亿,百亿,千亿,万亿,十万亿,百万亿,千万亿,兆
因而,一万是104,一亿是108,一兆是1016
QString int2ChnsNum(qint64 num) {
QStringList int2cnNum = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
if (num < 10)
return int2cnNum.value(num);
QStringList cnNumWeight = { "","十", "百", "千" };
std::function<QStringList(const QStringList& cnNum, const QStringList& cnNumWeight, qint64 numb)> recu = [&](const QStringList& cnNum, const QStringList& cnNumWeight, qint64 numb)->QStringList {
QStringList res;
QString rr;
QList<QPair<qint64, QString>> mp = { {9999999999999999, "兆"},{99999999,"亿"},{9999,"万"} };
qint64 restNum;
for (QPair<qint64, QString>& cump : mp) {
if (numb > cump.first) {
qint64 dig = numb % (cump.first + 1);
if (dig) {
res.append(recu(cnNum, cnNumWeight, dig));
}
qint64 rest = numb / (cump.first + 1);
if (rest) {
QStringList t = recu(cnNum, cnNumWeight, rest);
t.append(cump.second);
t.append(res);
res = t;
}
break;
} else if (numb < 10000) {
int tn = numb;
for (int w = 0; w < 4; ++w) {
int d = numb % 10;
numb /= 10;
if (d && !cnNumWeight.value(w).isEmpty())
res.prepend(cnNumWeight.value(w));
res.prepend(cnNum.value(d));
}
}
}
return res;
};
// 中间的多个“零”合并成一个零,去除开头和结尾的“零”
QString res = recu(int2cnNum, cnNumWeight, num).join("");
res.replace(QRegularExpression("零{2,}"), "零").replace("零万", "万").replace("零亿", "亿").replace("零兆", "兆");
if (res.startsWith("零"))
res.remove(0, 1);
if (res.startsWith("一十"))
res.remove(0, 1);
if (res.endsWith("零"))
res.remove(res.count() - 1, 1);
// 整几千的时候不需要“零”
QRegularExpression re("零(.{1})千");
int idx = res.lastIndexOf(re);
while (idx > -1) {
res.remove(idx, 1);
idx = res.lastIndexOf(re);
}
return res;
}
main.cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList res;
qint64 num = 9223300000000705817;
qDebug() << int2ChnsNum(num);
return app.exec();
}
输出
九百二十二兆三千三百万亿零七十万五千八百一十七