上篇文章介绍了转换十万以内的数字,经过扩展现在可以支持千亿级别的数字,主要增加了万和亿的衔接处理。
JavaScript:
function ch_num (n) {
var tab = [ 12, 11, 10, 14, 12, 11, 10, 13, 12, 11, 10 ];//单位表
var i, j, k, num = new Array (12).fill (0);
var ch = new Array (24).fill (0);
k = 0;
if (n <= 10) {//10以下,直接返回结果
ch [k++] = n;
return {k, ch};
}
if (n < 20) {//20以下,补十后返回结果
ch [k++] = 10;
ch [k++] = n - 10;
return {k, ch};
}
for (i = 0; i < 12; i++) {//按10进制提取12位,右对齐
if (n > 0) {
num [11 - i] = n % 10;
n = (n - num [11 - i]) / 10;
} else {
break;
}
}
for (i = 12 - i; i < 12; i++) {//遍历
if (num [i] == 0) {//遇到0
for (j = i; j < 12; j++) {//循环处理0
if (num [j] == 0) {
if (j < 8 && j % 4 == 3 && j - i < 3) ch [k++] = tab [j];//补万或亿
if (j == 11) i = 11;//直到末尾还是0,结束
} else {//遇到数字,前补零,后补单位,结束循环处理0
ch [k++] = 0;
ch [k++] = num [j];
if (j < 11) ch [k++] = tab [j];//个位不加单位
i = j;
break;
}
}
} else {//遇到数字,补单位
ch [k++] = num [i];
if (i < 11) ch [k++] = tab [i];//个位不加单位
}
}
return {k, ch};
}
function obj2str ({k, ch}) {
var i, str = "";
var tab = [ "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "百", "千", "万", "亿" ];
for (i = 0; i < k; i++) {
str += tab [ch [i]];
}
return str;
}
obj2str (ch_num (999999999999));
C语言:
#include <stdio.h>
unsigned char ch_num (unsigned char *ch, unsigned long long n) {
unsigned char i, j, k, num [12], tab [] = { 12, 11, 10, 14, 12, 11, 10, 13, 12, 11, 10 };//单位表
k = 0;
if (n <= 10) {//10以下,直接返回结果
ch [k++] = n;
return k;
}
if (n < 20) {//20以下,补十后返回结果
ch [k++] = 10;
ch [k++] = n - 10;
return k;
}
for (i = 0; i < 12; i++) {//按10进制提取12位,右对齐
if (n > 0) {
num [11 - i] = n % 10;
n = n / 10;
} else {
break;
}
}
for (i = 12 - i; i < 12; i++) {//遍历
if (num [i] == 0) {//遇到0
for (j = i; j < 12; j++) {//循环处理0
if (num [j] == 0) {
if (j < 8 && j % 4 == 3 && j - i < 3) ch [k++] = tab [j];//补万或亿
if (j == 11) i = 11;//直到末尾还是0,结束
} else {//遇到数字,前补零,后补单位,结束循环处理0
ch [k++] = 0;
ch [k++] = num [j];
if (j < 11) ch [k++] = tab [j];//个位不加单位
i = j;
break;
}
}
} else {//遇到数字,补单位
ch [k++] = num [i];
if (i < 11) ch [k++] = tab [i];//个位不加单位
}
}
return k;
}
void print_ch_num (unsigned char k, unsigned char *ch) {
unsigned char i;
char tab [][4] = { "零\0", "一\0", "二\0", "三\0", "四\0", "五\0", "六\0", "七\0", "八\0", "九\0", "十\0", "百\0", "千\0", "万\0", "亿\0" };
for (i = 0; i < k; i++) {
printf("%s", tab [ch [i]]);
}
printf("\n");
}
void main ()
{
unsigned char k, ch[24];
k = ch_num (ch, 999999999999);
print_ch_num (k, ch);
}