论坛首页 Java企业应用论坛

将阿拉伯数字转换成中文金额大写

浏览 5975 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-03-05  
前段时间在javaeye上看到一篇关于将数字转换成中文金额大写文章:将数字转换成中文金额大写形式(Java版),写得很不错,我也来写一个,我觉得这个算法比其更简单有效。闲话少说,大家看代码吧,代码很简单。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CurrencyConverter {

	private static final double MAXIMUM_NUMBER = 9999999999999.99d;

	private static final String CN_ZERO = "零";
	private static final String CN_SYMBOL = "¥:";
	private static final String CN_DOLLAR = "圆";
	private static final String CN_INTEGER = "整";

	private static final String[] digits = new String[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
	private static final String[] radices = new String[] { "", "拾", "佰", "仟" };
	private static final String[] bigRadices = new String[] { "", "万", "亿", "万" };
	private static final String[] decimals = new String[] { "角", "分" };

	public static void main(String[] args) {

		// 键盘输入数字
		String currencyDigits = input();
		// 检查数字合法性
		if (check(currencyDigits)) {
			//转换大写并输出
			System.out.println(convert(currencyDigits));
		}
	}

	/**
	 * 转换大写
	 * 
	 * @param currencyDigits
	 * @return
	 */
	public static String convert(String currencyDigits) {

		String integral = null; // 整数部分
		String decimal = null; // 小数部分
		String outputCharacters = null; // 最终转换输出结果

		String d = null;
		int zeroCount = 0, p = 0, quotient = 0, modulus = 0;

		// 删除数字中的逗号,
		currencyDigits = currencyDigits.replace("/,/g", "");
		// 删除数字左边的0
		currencyDigits = currencyDigits.replace("/^0+/", "");

		// 拆分数字中的整数与小数部分
		String[] parts = currencyDigits.split("\\.");
		if (parts.length > 1) {
			integral = parts[0];
			decimal = parts[1];

			// 如果小数部分长度大于2,四舍五入,保留两位小数
			if (decimal.length() > 2) {
				long dd = Math.round(Double.parseDouble("0."+decimal) * 100) ;
				decimal = Long.toString(dd);
			}

		} else {
			integral = parts[0];
			decimal = "0";
		}

		// Start processing:
		outputCharacters = "";
		// Process integral part if it is larger than 0:
		if (Double.parseDouble(integral) > 0) {

			zeroCount = 0;

			for (int i = 0; i < integral.length(); i++) {

				p = integral.length() - i - 1;
				d = integral.substring(i, i + 1);

				quotient = p / 4;
				modulus = p % 4;
				if (d.equals("0")) {
					zeroCount++;
				} else {
					if (zeroCount > 0) {
						outputCharacters += digits[0];
					}
					zeroCount = 0;
					outputCharacters += digits[Integer.parseInt(d)] + radices[modulus];
				}
				if (modulus == 0 && zeroCount < 4) {
					outputCharacters += bigRadices[quotient];
				}
			}
			outputCharacters += CN_DOLLAR;
		}

		// Process decimal part if it is larger than 0:
		if (Double.parseDouble(decimal) > 0) {
			for (int i = 0; i < decimal.length(); i++) {
				d = decimal.substring(i, i + 1);
				if (!d.equals("0")) {
					outputCharacters += digits[Integer.parseInt(d)] + decimals[i];
				} else {
					if (i == 0) {
						outputCharacters += CN_ZERO;
					}
				}
			}
		}
		
		// Confirm and return the final output string:
		if (outputCharacters.equals("")) {
			outputCharacters = CN_ZERO + CN_DOLLAR;
		}
		if (decimal == null || decimal.equals("0")) {
			outputCharacters += CN_INTEGER;
		}

		outputCharacters = CN_SYMBOL + outputCharacters;
		return outputCharacters;
	}

	/**
	 * 从键盘输入要转换的数字
	 * 
	 * @return
	 */
	private static String input() {

		System.out.println("请输入一个数字(精确到小数点后两位):");
		Scanner scanner = new Scanner(System.in);
		String currencyDigits = scanner.next();
		scanner.close();
		return currencyDigits;
	}

	/**
	 * 检查输入数字的合法性
	 * 
	 * @param currencyDigits
	 * @return
	 */
	private static boolean check(final String currencyDigits) {
		if (currencyDigits == null || currencyDigits.trim().equals("")) {
			System.out.println("没有输入要转换的数字");
			return false;
		}

		Pattern pattern = Pattern.compile("/[^,.\\d]/", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(currencyDigits);

		if (matcher.find()) {
			System.out.println("数字中含有非法字符!");
			return false;
		}

		pattern = Pattern.compile("/^((\\d{1,3}(,\\d{3})*(.((\\d{3},)*\\d{1,3}))?)|(\\d+(.\\d+)?))$/",
				Pattern.CASE_INSENSITIVE);
		matcher = pattern.matcher(currencyDigits);
		if (matcher.find()) {
			System.out.println("错误的数字格式!");
			return false;
		}

		if (Double.parseDouble(currencyDigits) > MAXIMUM_NUMBER) {
			System.out.println("超出转换最大范围!");
			return false;
		}

		return true;
	}
}
   发表时间:2011-04-17  
建议看看这个代码

http://bardo.iteye.com/admin/blogs/983559
0 请登录后投票
   发表时间:2011-04-17  
恩,就是注释少了点,有点看不懂,本人新手~
0 请登录后投票
   发表时间:2011-07-21  
参考了一个前辈写的,代码如下:
import java.util.Scanner;

public class MoneyConvert {

static Scanner san = new Scanner(System.in);

private static String HanDigiStr[] = new String[] { "零", "壹", "贰", "叁",
"肆", "伍", "陆", "柒", "捌", "玖" };

private static String HanDiviStr[] = new String[] { "", "拾", "佰", "仟", "万",
"拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾",
"佰", "仟", "万", "拾", "佰", "仟" };

public static void main(String[] args) {
System.out.println("请输入一个要转化的值:");
double db = san.nextDouble();
System.out.println(NumToRMBStr(db));

}



public static String NumToRMBStr(double val) {
String SignStr = "";
String TailStr = "";
long fraction, integer;
int jiao, fen;

if (val < 0) {
val = -val;
SignStr = "负";
}
if (val > 99999999999999.999 || val < -99999999999999.999)
return "数值位数过大!";
// 四舍五入到分
long temp = Math.round(val * 100);
integer = temp / 100;
fraction = temp % 100;
jiao = (int) fraction / 10;
fen = (int) fraction % 10;
if (jiao == 0 && fen == 0) {
TailStr = "整";
} else {
TailStr = HanDigiStr[jiao];
if (jiao != 0)
TailStr += "角";
if (integer == 0 && jiao == 0) // 零元后不写零几分
TailStr = "";
if (fen != 0)
TailStr += HanDigiStr[fen] + "分";
}

// 下一行可用于非正规金融场合,0.03只显示“叁分”而不是“零元叁分”
// if( !integer ) return SignStr+TailStr;

return "¥" + SignStr + PositiveIntegerToHanStr(String.valueOf(integer))
+ "元" + TailStr;
}


private static String PositiveIntegerToHanStr(String NumStr) { // 输入字符串必须正整数,只允许前导空格(必须右对齐),不宜有前导零
String RMBStr = "";
boolean lastzero = false;
boolean hasvalue = false; // 亿、万进位前有数值标记
int len, n;
len = NumStr.length();
if (len > 15)
return "数值过大!";
for (int i = len - 1; i >= 0; i--) {
if (NumStr.charAt(len - i - 1) == ' ')
continue;
n = NumStr.charAt(len - i - 1) - '0';
if (n < 0 || n > 9)
return "输入含非数字字符!";

if (n != 0) {
if (lastzero)
RMBStr += HanDigiStr[0]; // 若干零后若跟非零值,只显示一个零
// 除了亿万前的零不带到后面
// if( !( n==1 && (i%4)==1 && (lastzero || i==len-1) ) ) //
// 如十进位前有零也不发壹音用此行
//modify  by  xym 2009-11-03
//if (!(n == 1 && (i % 4) == 1 && i == len - 1)) // 十进位处于第一位不发壹音
RMBStr += HanDigiStr[n];
RMBStr += HanDiviStr[i]; // 非零值后加进位,个位为空
hasvalue = true; // 置万进位前有值标记

} else {
if ((i % == 0 || ((i % == 4 && hasvalue)) // 亿万之间必须有非零值方显示万
RMBStr += HanDiviStr[i]; // “亿”或“万”
}
if (i % 8 == 0)
hasvalue = false; // 万进位前有值标记逢亿复位
lastzero = (n == 0) && (i % 4 != 0);
}

if (RMBStr.length() == 0)
return HanDigiStr[0]; // 输入空字符或"0",返回"零"
return RMBStr;
}
}
0 请登录后投票
   发表时间:2011-09-03  
请输入一个数字(精确到小数点后两位):
1000000001010
¥:壹万零壹仟零壹拾圆整
在亿单位上前3为零的情况下 应该加上处理
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics