- class MoneyFormat{
- private final String [] pattern ={"零","壹","貳","叄","肆","伍","陸","柒","捌","玖"};
- private final String [] cPattern ={"","拾","佰","仟","萬","拾","佰","仟","億"};
- private final String [] cfPattern = {"","角","分"};
- private final String ZEOR = "零";
- public MoneyFormat(){
- System.out.println("run...");
- }
- public String format(String moneyString){
- int dotPoint = moneyString.indexOf("."); //判斷是否爲小數
- String moneyStr;
- if(dotPoint != -1){
- moneyStr = moneyString.substring(0,moneyString.indexOf("."));
- }
- else{
- moneyStr = moneyString;
- }
- StringBuffer fraction = null; //小數部分的處理,以及最後的yuan.
- StringBuffer ms = new StringBuffer();
- for(int i = 0;i < moneyStr.length();i++){
- ms.append(pattern[moneyStr.charAt(i) - 48]); //按數組的編號加入對應大寫漢字
- }
- int cpCursor = 1;
- for(int j = moneyStr.length() - 1;j > 0;j--){
- ms.insert(j,cPattern[cpCursor]); //在j之後加字符,不影響j對原字符串的相對位置
- //只是moneyStr.length()不斷增加
- //insert(j,"string")就在j位置處插入,j=0時爲第一位
- cpCursor = cpCursor == 8?1:cpCursor + 1; //億位之後重新循環
- }
- while(ms.indexOf("零拾") != -1){ //當十位爲零時用一個"零"代替"零拾"
- //replace的起始於終止位置
- ms.replace(ms.indexOf("零拾"),ms.indexOf("零拾") + 2,ZEOR);
- }
- while(ms.indexOf("零佰") != -1){ //當百位爲零時,同理
- ms.replace(ms.indexOf("零佰"),ms.indexOf("零佰") + 2,ZEOR);
- }
- while(ms.indexOf("零仟") != -1){ //同理
- ms.replace(ms.indexOf("零仟"),ms.indexOf("零仟") + 2,ZEOR);
- }
- while(ms.indexOf("零萬") != -1){ //萬需保留,中文習慣
- ms.replace(ms.indexOf("零萬"),ms.indexOf("零萬") + 2,"萬");
- }
- while(ms.indexOf("零億") != -1){ //同上
- ms.replace(ms.indexOf("零億"),ms.indexOf("零億") + 2,"億");
- }
- while(ms.indexOf("零零") != -1){//有連續數位出現零,即有以下情況,此時根據習慣保留一個零即可
- ms.replace(ms.indexOf("零零"),ms.indexOf("零零") + 2,ZEOR);
- }
- while(ms.indexOf("億萬") != -1){ //特殊情況,如:100000000,根據習慣保留高位
- ms.replace(ms.indexOf("億萬"),ms.indexOf("億萬") + 2,"億");
- }
- while(ms.lastIndexOf("零") == ms.length()-1){ //當結尾爲零j,不必顯示,經過處理也只可能出現一個零
- if(ms.indexOf("零") == -1){
- ms.delete(ms.lastIndexOf("零"),ms.lastIndexOf("零") + 1);
- }else{
- break;
- }
- }
- int end;
- if((dotPoint = moneyString.indexOf(".")) != -1 ){ //是小數的進入
- String fs = moneyString.substring(dotPoint + 1,moneyString.length());
- if(fs.indexOf("00") == -1 || fs.indexOf("00") >= 2){//若前兩位小數全爲零,則跳過操作
- end = fs.length() > 2?2:fs.length(); //僅保留兩位小數
- fraction = new StringBuffer(fs.substring(0,end));
- for(int j = 0;j < fraction.length();j++){
- fraction.replace(j,j+1,this.pattern[fraction.charAt(j) - 48]); //替換大寫漢字
- }
- for(int i = fraction.length();i > 0;i--){ //插入中文標識
- fraction.insert(i,cfPattern[i]);
- }
- fraction.insert(0,"元"); //爲整數部分添加標識
- }
- else{
- fraction = new StringBuffer("元整");
- }
- }
- else{
- fraction = new StringBuffer("元整");
- }
- ms.append(fraction); //加入小數部分
- return ms.toString();
- }
- public static void main(String [] ar){
- System.out.println(new MoneyFormat().format("10005022.123009"));
- System.out.println(new MoneyFormat().format("0.12"));
- }
- }
轉自【http://www.open-open.com/lib/view/open1400206687504.html】