阿拉伯数字转中文

/ java / 没有评论 / 351浏览

在平常的工作中,特别是涉及到钱时,大写的中文数字是经常遇到的,可是,大写的中文数字汉字又比较难于记忆和书写。

Java代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 阿拉伯数字转中文
 * @author Administrator
 *
 */
public class Test005 {
	/*static String cha[] = {"零","一","二","三","四","五","六","七","八","九"};	
	static String cha2[] = {"","十","百","千"};
	static String cha3[] = {"","万","亿","万亿","亿亿","万亿亿"};*/
	
	static String cha[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
	static String cha2[] = {"","拾","佰","仟"};
	static String cha3[] = {"","万","亿","万亿","亿亿","万亿亿"};
	
	public static void main(String[] args) {
		System.out.println("转成中文:" + transformNumber("1582000400080"));
	}
	
	//判断是否是合法数字
	public static boolean isNumber(String str){
		boolean result = false;
		if(str==null||str.length()==0)
			return result;
		
		int length = str.length();
		if(length==1){
			if(str.equals("0"))
				result = true;			
		}else{
			Pattern pattern = Pattern.compile("[1-9]+[0-9]*");  
			Matcher isNum = pattern.matcher(str);
			result = isNum.matches();
		}
		return result;
	}
	
	//判断是不是全是0
	public static boolean isZero(String str){
		boolean result = false;
		Pattern pattern = Pattern.compile("0*");  
		Matcher isNum = pattern.matcher(str);
		result = isNum.matches();
		return result;
	}
	
	//四位数以内阿拉伯转中文(并非真正中文数字)
	public static String transform(String str){
		if(str.length()==1)
			return cha[Integer.parseInt(str)];
		StringBuffer result = new StringBuffer();		
		String tem[] = str.split("");
		for(int n=0;n<tem.length;n++){			
			int m = Integer.parseInt(tem[n]);
			if(m==0){
				String tem2 = str.substring(n);
				if(isZero(tem2)){
					//后面全是0不处理
				}else if((tem.length-1)==n){
					//最后一位是0不处理
				}else if(n==0){
					//首位是0加零
					result.append(cha[0]);
				}else if(tem[n-1].equals("0")){
					//前一位是0不处理
				}else{
					//其他是0加零
					result.append(cha[0]);
				}
			}else{
				result.append(cha[m]).append(cha2[tem.length-n-1]);
			}
		}
		return result.toString();
	}
	
	public static String transformNumber(String str){
		System.out.println("字符串是:" + str);
		if(!isNumber(str))
			return "不是合法字符";
		if(str.length()>20)
			return "字符太长";
		StringBuffer result = new StringBuffer();
		//把数字转成4位一组的数组
		int length = str.length();
		int mo = (int) Math.ceil(length/4.0);
		String ch[] = new String[mo];
		for(int n=0;n<mo;n++){
			int i = length - 4 * n;
			int j = (length - 4) - 4 * n;
			if(j<0)
				j = 0;
			ch[n] = str.substring(j, i);
		}
		for(int n=ch.length;n>0;n--){
			if(!isZero(ch[n-1]))
				result.append(transform(ch[n-1])).append(cha3[n-1]);
		}
		return result.toString();
	}
}

程序结果

字符串是:1582000400080

转成中文:壹万亿伍仟捌佰贰拾亿零肆拾万零捌拾

点击这里给我发消息
嘿!有什么能帮到您的吗?