import java.math.*; java public class TestTrans { app private static final String NUM= "零壹貳叄肆伍陸柒捌玖" ; ui private static final String UNIT= "億仟佰拾萬仟佰拾元角分釐毫" ; //13位 spa private static final String EX_UNIT= "億拾佰仟萬" ; code //將數值串轉換成大寫金額:一個循環就好了 orm //若數值串非法,則返回:null ci public static String toCapNumber(String data) get { it String s=checkValue(data); io if (s== null ){ return null ;} //數值串非法 if (s.charAt( 0 )== '0' ){ return "零元整" ;} String rs= "" ; //最終結果串 boolean hasZero= false ; //有零沒有輸出,則置爲true int i= 0 ,sLen=s.length(),uLen=UNIT.length(); int pos=uLen-sLen+i; //i所對應的單位串中的位置 for (;i<sLen;i++,pos++) //一個循環,即求出全部的大寫金額串 { if (s.charAt(i)== '0' ) //如果字符'0' { hasZero= true ; if (isUnit(i,sLen)) //若對應單位是'億'、萬、元,則輸出。 { String u=getUnit(i, sLen); if (u.endsWith( "億" )&&!rs.endsWith( "億" )|| u.endsWith( "萬" )&&!rs.endsWith( "億" )|| u.endsWith( "元" ) ) { rs=rs+getUnit(i, sLen); //將單位輸出 hasZero= false ; } } } else { //不是'0' if (hasZero){rs=rs+ "零" ;hasZero= false ;} rs=rs+NUM.charAt(s.charAt(i)- '0' )+getUnit(i, sLen); } } //for(i) 大寫金額轉換結束 if ( "分釐毫" .indexOf(rs.charAt(rs.length()- 1 ))==- 1 ) //補整 { rs=rs+ "整" ; } return rs; } //大寫金額轉換結束 //檢查數值串。不正確返回null。不然返回整數值串(小數點向右移4位) private static String checkValue(String data) { BigDecimal bd= null ; BigInteger bi= null ; try { bd= new BigDecimal(data,MathContext.DECIMAL128).movePointRight( 4 ); } catch (NumberFormatException e){ return null ;} bi=(bd.add( new BigDecimal( 0.5 ))).toBigInteger(); return bi.toString(); } //當前位置對應的單位如果億、萬、元,則返回true private static boolean isUnit( int pos, int len) { String u=getUnit(pos, len); return u.endsWith( "億" )||u.endsWith( "萬" )||u.endsWith( "元" ); } //返回當前位置對應的單位 private static String getUnit( int pos, int len) { int upos=UNIT.length()-len+pos; if (upos< 0 ) { upos=-upos; if (upos% 5 == 0 ){ return getStr(upos/ 5 );} return "" +EX_UNIT.charAt(upos% 5 ); } return "" +UNIT.charAt(upos); } //返回:億、億億、億億億、億億億億、。。。。。 private static String getStr( int i) { StringBuilder sb= new StringBuilder( "億" ); for ( int j= 1 ;j<=i;j++) { sb.append( '億' ); } return sb.toString(); } public static void main(String[] args) { System.out.println( "0.000=>" +toCapNumber( "0.000" )); System.out.println( "0.50000=>" +toCapNumber( "0.50000" )); System.out.println( "0.056478154e3=>" +toCapNumber( "0.056478154e3" )); System.out.println( "2000300004000.5600=>" +toCapNumber( "2000300004000.5600" )); System.out.println( "30000000002000000000.234=>" +toCapNumber( "30000000002000000000.234" )); } } |