java實現金錢數字轉大寫
阿新 • • 發佈:2018-12-29
private static final char [] ChineseNum ={'零','壹','貳','叄','肆','伍','陸','柒','捌','玖'}; private static final char [] ChineseUnit={'裡','分','角','元','拾','佰','仟','萬','拾','佰','仟','億','拾','佰','仟'}; /** * 返回關於錢的中文式大寫數字,支僅持到億 * */ public static String arabNumToChineseRMB(int moneyNum){ String res=""; int i=3; if(moneyNum==0) return "零元"; while(moneyNum>0){ res=ChineseUnit[i++]+res; res=ChineseNum[moneyNum%10]+res; moneyNum/=10; } return res.replaceAll("零[拾佰仟]", "零") .replaceAll("零+億", "億").replaceAll("零+萬", "萬") .replaceAll("零+元", "元").replaceAll("零+", "零"); } /** * 返回關於錢的中文式大寫數字,支僅持到億 * @throws Exception * */ private static String arabNumToChineseRMB(String moneyNum) throws Exception{ String res=""; int i=3; int len=moneyNum.length(); if(len>12){ throw new Exception("Number too large!"); } if("0".equals(moneyNum)) return "零元"; //System.out.println(moneyNum); for(len--;len>=0;len--){ res=ChineseUnit[i++]+res; int num=Integer.parseInt(moneyNum.charAt(len)+""); res=ChineseNum[num]+res; } return res.replaceAll("零[拾佰仟]", "零") .replaceAll("零+億", "億").replaceAll("零+萬", "萬") .replaceAll("零+元", "元").replaceAll("零+", "零"); } /** * 整數位支援12位,到仟億 * 支援到小數點後3位,如果大於3位,那麼會四捨五入到3位 * @throws Exception * */ public static String arabNumToChineseRMB(double moneyNum) throws Exception{ String res=""; String money=String.format("%.3f",moneyNum); //System.out.println(money); int i=0; if(moneyNum==0.0) return "零元"; String inte = money.split("\\.")[0]; int deci=Integer.parseInt(money.split("\\.")[1].substring(0, 3)); while(deci>0){ res=ChineseUnit[i++]+res; res=ChineseNum[deci%10]+res; deci/=10; } res=res.replaceAll("零[裡分角]", "零"); if(i<3) res="零"+res; res=res.replaceAll("零+", "零"); if(res.endsWith("零")) res=res.substring(0, res.length()-1); return arabNumToChineseRMB(inte)+res; }