本帖最后由 hello_csu 于 2015-1-4 23:11 编辑
的确该题有点难度,主要考虑两个点:
1,怎么存数据处理。其中分为GroupLevel和UnitLevel(千,百,十,个)处理。
2,怎么删除多余的零,单位,该部分用到正则表达式。其代码如下:
- import java.util.*;
- import java.math.*;
- import java.util.regex.*;
- public class TestDemo {
-
- static final long CONST_DIV = 10000;
- public static void main(String[] agrs) {
- print(convertChineseFormat("101000001010"));
- }
- /**
- * 金额转换,阿拉伯数字转换成中国传统形式。
- * 例如:101000001010 转换为 壹仟零壹拾亿零壹仟零壹拾圆整
- * @param o
- */
- public static String convertChineseFormat(String num) {
- Character ch[] = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
- Character money_unit[] ={'圆', '拾', '佰', '仟' };
- Character big_money_unit[] ={ '万','億','兆' };
- String replaceregx[] = {"零圆","零拾","零圆","零佰","零仟","零万","零億","零兆"};
- String targetstr[] = {"圆","拾","圆","佰","仟","万","億","兆"};
- final int UNITLEVEL_MAX = 4;
- BigInteger bignum= new BigInteger(num);
- String format = null;
- StringBuilder strbuilder = new StringBuilder();
- int unitlevel = 0; //每次处理4位
- int grouplevel = 0 ;//处理到哪有级别的四位
-
- while(!bignum.equals(BigInteger.ZERO)) {
- int value = bignum.remainder(BigInteger.TEN).intValue();
- if(unitlevel == UNITLEVEL_MAX) {
- strbuilder.append(big_money_unit[grouplevel]);
- unitlevel = 0;
- grouplevel++;
- }else {
- if(value != 0) {
- if((unitlevel == 0)&&(grouplevel==0)) {
- strbuilder.append('整');
- }
- strbuilder.append(money_unit[unitlevel]);
- }else {
- if((unitlevel == 0)&&(grouplevel==0)) {
- strbuilder.append('整');
- strbuilder.append(money_unit[unitlevel]);
- }
- }
- }
- strbuilder.append(ch[value]);
- unitlevel++;
- bignum = bignum.divide(BigInteger.TEN);
-
- }
-
- //pattern match to delete the 0.
- format =strbuilder.reverse().toString();
- format = format.replaceAll("(零)\\1+","零");
-
- //replace 零[unit]->[unit]
- format = format.replaceAll("零([圆拾佰仟万億兆])","$1");
-
- format = format.replaceAll("([万億兆])([万億兆])+","$1\\零");
-
- return format;
- }
-
- public static void print(Object e) {
- System.out.println(e);
- }
- }
复制代码
|