`
seaoop
  • 浏览: 15442 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

[Java面试题]将金额转换为RMB大写形式

阅读更多

经常出现的一道面试题,将金额转换为RMB大写形式,如不懂题目意思可上网搜搜该题目,下面是我自己写的代码:

 

package com.wuhaiming;

/**
 * 将金额转换为RMB大写形式.</p>
 * @author wuhaiming
 * @version V1.0 
 * @date 2010-10-14下午04:20:13
 */
public class Amount2RMB 
{
	//大写金额
	private static char[] NUMBER_CHAR = "零壹贰叁肆伍陆柒捌玖".toCharArray();
	//金额单位
	private static char[] UNIT_CHAR = "元拾佰仟万拾佰仟亿拾佰仟".toCharArray();

	/**
	 * @author: wuhaiming
	 * @Title convert
	 * @Time: 2010-10-14下午04:25:18
	 * @Description: 将数字转换为金额
	 * @throws: 
	 * @param amount 小写金额
	 * @return: String 大写金额
	 */
	public static String convert(int amount)
	{
		StringBuffer amountStr = new StringBuffer();
		
		if(amount > 9)
		{
			//当前位置
			int pos = 0;
			//当前位置所表示的值
			int digit = amount % 10;
			//上一位置所表示的值
			int preDigit = -1;
			
			while(amount > 0)
			{
				//如果个位为0的话则只输出单位
				if(pos == 0 && digit == 0)
				{
					amountStr.insert(0, UNIT_CHAR[pos]);
				}
				else
				{
					//如果位置为万或者为亿的位置,就算当前位置值为0也要输出
					//如12,000,675
					if((pos == 4 || pos ==8) && digit == 0)
					{
						amountStr.insert(0, UNIT_CHAR[pos]);
					}
					else
					{
						//如果上一个位置与当前位置的值不同时为0的情况下
						//过滤掉重复的0
						if(digit != 0 || preDigit != 0)
						{
							//如果当前位置为0上一个位置不为0的情况下,则只输出数字,不需要单位
							if(digit == 0 && preDigit != 0)
							{
								amountStr.insert(0, NUMBER_CHAR[digit]);
							}
							else
							{
								amountStr.insert(0, UNIT_CHAR[pos]);
								amountStr.insert(0, NUMBER_CHAR[digit]);
							}
						}
					}
				}
				
				amount = amount / 10;
				pos++;
				preDigit = digit;
				digit = amount % 10; 
			}
			
			return amountStr.toString().replaceAll("亿万", "亿");
		}
		else
		{
			return amountStr.append(NUMBER_CHAR[amount]).append(UNIT_CHAR[0]).toString();
		}
	}
	
	public static void main(String[] args)
	{
		//备注:在这里就不对参数进行检验,即默认传过来的参数是正确的金额
		System.out.println(convert(100324500));
	}
	
}

 

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics