码迷,mamicode.com
首页 > 其他好文 > 详细

金额转换成大写

时间:2015-01-31 19:24:46      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:金额转换   java   正则表达式   

import java.text.DecimalFormat;
import java.util.Scanner;

/**  
 * @Description: 金额转换成大写
 * @author huangzjb
 * @mail cblue2013@126.com
 * @Company Digital China
 * @date 2015-1-30
 */

public class ChineseCurrency {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("请输入人民币金额:");
		
		while (true) {
			double number = s.nextDouble();
			if(number > 10000000000000000.0) 
				{
					System.out.println("金额太大,超出16位最大的整数!");
					continue;
				}
			System.out.println(toChineseCurrency(new Double(number)));
		}
	}

	public static String toChineseCurrency(Number number) {
		String targetNumber = new DecimalFormat("#.00").format(number);
		String result = "";
		
		targetNumber = targetNumber.replaceAll("\\.", "");
		char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
		String unit = "仟佰拾兆仟佰拾亿仟佰拾万仟佰拾元角分";
		int unitLength = unit.length();
		StringBuffer unitSb = new StringBuffer(unit);
		StringBuffer resultSb = new StringBuffer(result);
		for (int i = targetNumber.length() - 1; i >= 0; i--){
			resultSb = unitSb.insert(unitLength - targetNumber.length() + i, digit[(targetNumber.charAt(i) - 0x30)]);//根据金额数字所在的位置,把它们对应的大写汉字和后面的单位('万仟佰拾...')拼接起来
		}
		
		result = resultSb.toString();
		//System.out.println((l + s.length() )== sb.length());
		
		result = result.substring(unitLength - targetNumber.length(), unitLength + targetNumber.length());//根据金额数字的长度,把前面超出范围的单位截掉(比如234.12,要把前面的'仟佰拾兆仟佰拾亿仟佰拾万仟'去掉..)
		//System.out.println(result);
		
		/*result = result.replaceAll("零[拾佰仟]", "零").replaceAll("零{2,}", "零")
		.replaceAll("零([兆亿万元])", "$1").replaceAll("零[角分]", "");*/
		
		result = result.replaceAll("零[拾佰仟]", "零")
		.replaceAll("零{2,}", "零")//有多个零连在一起,只取一个零
		.replaceAll("([拾佰仟])零([兆亿万])", "$1$2")//可以理解为把金额从低位到高位分为四组,每组四位,这一步是去除每一组(不全为零)末尾的零
		.replaceAll("零[兆亿万]", "")//处理四位数全为零的组
		.replaceAll("零元", "元"). replaceAll("零[角分]", "");
		
		if (result.endsWith("角"))
			result += "零分";
		if (!result.contains("角") && !result.contains("分") && result.contains("元"))
			result += "整";
		if (result.contains("分") && !result.contains("整") && !result.contains("角"))
			result = result.replace("元", "元零");
		return result;
	}
}

金额转换成大写

标签:金额转换   java   正则表达式   

原文地址:http://blog.csdn.net/hzj9118/article/details/43342897

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!