刚申请的博客,写几个小程序练练手,也正好充一下门面,呵呵,欢迎指正
package com.drug.test;
public class NumUtil {
public static String num2Chinese(long num) {
StringBuilder s = new StringBuilder();
// 输出long类型的最小值
if (num == Long.MIN_VALUE)
return "负玖佰贰拾贰京叁仟叁佰柒拾贰兆零叁佰陆拾捌亿伍仟肆佰柒拾柒万伍仟捌佰零捌";
// 处理负值
if (num < 0) {
s.append("负");
num = -num;
}
// 把数字强行转换成字符串
String num_str = num + "";
String unit = "万亿兆京";
// 对多余部分进行单独转换
int num_l = num_str.length();
int uint_i = (num_l - 1) / 4;
if (num_l % 4 != 0) {
s.append(num2C(num_str.substring(0, num_l % 4)));
if (uint_i > 0)
s.append(unit.charAt(--uint_i));
num_str = num_str.substring(num_l % 4);
}
// 对数字进行切分,每4个一组进行转换
for (int i = 0; i < num_str.length(); i = i + 4) {
String subNum = num2C(num_str.substring(i, i + 4));
s.append(subNum);
uint_i--;
if (uint_i > -1 && !(subNum == null || subNum.length() == 0))
s.append(unit.charAt(uint_i));
}
return s.toString();
}
// 进行万以内的转换,
private static String num2C(String num) {
String num_cn = "零壹贰叁肆伍陆柒捌玖";
StringBuilder s = new StringBuilder();
// 是否舍弃零
boolean isDrop = true;
for (int i = num.length() - 1, k = 0; i > -1; i--, k++) {
int j = num.charAt(i) - 48;
if (j == 0) {
if (isDrop)
continue;
else {
s.append(num_cn.charAt(j));
isDrop = true;
}
} else {
if (k == 1)
s.append("拾");
else if (k == 2)
s.append("佰");
else if (k == 3)
s.append("仟");
s.append(num_cn.charAt(j));
isDrop = false;
}
}
// 字符串反转并返回
return s.reverse().toString();
}
public static void main(String[] args) {
long l = 10000000001l;
System.out.println(l);
System.out.println(num2Chinese(l));
}
}