数字转汉语读法

/**
 * @author yuhan
 * 
 */
public class Test {

	private static final char[] nums = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	private static final char[] fonts = new char[] { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };

	private enum NumFont {
		亿(100000000L), 万(10000L), 千(1000L), 百(100L), 十(10L);

		private final Long num;

		private NumFont(Long num) {
			this.num = num;
		}

		private Long getNum() {
			return num;
		}
	}

	/**
	 * 转换亿万千百十
	 */
	private static String transfer1(Long number) {
		StringBuilder sb = new StringBuilder();

		for (NumFont nf : NumFont.values()) {
			if (number / nf.getNum() > 0) {
				// 做除法之后整数部分递归继续读
				sb.append(transfer(number / nf.getNum()));
				sb.append(nf.name());
				// 余数继续读
				number = number % nf.getNum();
				// 如果下一位不够,则补0,整除则不补0,比如800,不能读八百零
				if (number < nf.getNum() / 10 && number != 0) {
					sb.append("0");
				}
			}
		}
		if (number > 0) {
			sb.append(number);
		}
		return sb.toString();
	}

	/**
	 * 转换0123456789
	 */
	private static char transfer2(char c) {
		char result = c;
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] == c) {
				result = fonts[i];
				break;
			}
		}
		return result;
	}

	/**
	 * 数字转换成汉语读法
	 */
	public static String transfer(Long number) {
		String result = transfer1(number);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < result.length(); i++) {
			char c = result.charAt(i);
			sb.append(transfer2(c));
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		System.out.println(transfer(108005000800L));
		System.out.println(transfer(13665543298L));
		System.out.println(transfer(53762L));
	}
}


你可能感兴趣的:(java)