将阿拉伯数字转换成中文(不带小数点)的思路:
1,定义一个存放单位的String数组("","十","百","千",...,"万亿"),再定义一个存放中文数字char数组('零','一','二',...'九'),定义一个int类型的数值num
static String[] units = { "", "十", "百", "千", "万", "十万", "百万", "千万", "亿",
"十亿", "百亿", "千亿", "万亿" };
static char[] numArray = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };
int num = 245000006;
2,调用String.valueOf(num).toCharArray()将num转成String类型再转成一个char数组,定义一个StringBuffer对象sb,获取char数组的长度length
char[] val = String.valueOf(num).toCharArray();
StringBuilder sb = new StringBuilder();
int length = val.length;
3,for循环遍历char的每一个元素,获取每一个元素的值并判断元素值是否为0,获取每一个元素对应的单位(length-1)-i
如果当前元素为0,则分两种情况,如果当前的下一个元素值为0则continue,如果不为0则在sb拼凑中文零
如果当元素不为0,则出sb拼凑当前元素值对象的中文和单位
for (int i = 0; i < len; i++) {
String m = val[i] + "";
int n = Integer.valueOf(m);
boolean isZero = n == 0;
String unit = units[(len - 1) - i];
if (isZero) {
if ('0' == val[i - 1]) {
//当前val[i]的下一个值val[i-1]为0则不输出零
continue;
} else {
//只有当当前val[i]的下一个值val[i-1]不为0才输出零
sb.append(numArray[n]);
}
} else {
sb.append(numArray[n]);
sb.append(unit);
}
}
return sb.toString();
完整代码:
public class NumberFormatTest {
static String[] units = { "", "十", "百", "千", "万", "十万", "百万", "千万", "亿",
"十亿", "百亿", "千亿", "万亿" };
static char[] numArray = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };
public static void main(String[] args) {
int num = 233200040;
String numStr = foematInteger(num);
print("num= " + num + ", 转换结果: " + numStr);
}
private static String foematInteger(int num) {
char[] val = String.valueOf(num).toCharArray();
int len = val.length;
System.out.println("----" + len);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
String m = val[i] + "";
int n = Integer.valueOf(m);
boolean isZero = n == 0;
String unit = units[(len - 1) - i];
if (isZero) {
if ('0' == val[i - 1]) {
//当前val[i]的下一个值val[i-1]为0则不输出零
continue;
} else {
//只有当当前val[i]的下一个值val[i-1]不为0才输出零
sb.append(numArray[n]);
}
} else {
sb.append(numArray[n]);
sb.append(unit);
}
}
return sb.toString();
}
}
输出结果:
num= 233200040, 转换结果: 二亿三千万三百万二十万零四十零