1. 程式人生 > >人民幣,大寫中文與數字之間轉換

人民幣,大寫中文與數字之間轉換

例:
輸入: 8.2
輸出: 八元二角

import java.util.Scanner;

public class RMBTest {

    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        while (scan.hasNext())
        {
            RMB r=new RMB(scan.next());
            r.show();
        }
    }
}

class RMB {
    private
String num[]={"零","一" ,"二" ,"三" ,"四" ,"五" ,"六" ,"七" ,"八" ,"九"}; private String unit[]={"釐","分","角","","十","百","千"}; private String a=""; private String b=""; boolean isZero=false; public RMB(String money) { int i=0; for(;i<money.length()&&money.charAt(i)!='.'
;i++) { a=a+money.charAt(i); } while(++i<money.length()) { b=b+money.charAt(i); } } public String divideByInteger() { String answer=""; if(!a.equals("0")) { answer=answer+ devideByHM(a)+"元"
; } if(!b.equals("")) { answer=answer + small(); } return answer; } public String small() { String answer=""; int n=2; boolean isZero=false; boolean firstZero=(b.charAt(0)=='0'&&a.equals("0")?true:false); for(int i=0;n-i>=0&&i<b.length();i++) { if(b.charAt(i)=='0') { isZero=true; continue; } if(isZero&&!firstZero) { answer=answer+num[0]+num[b.charAt(i)-'0']+unit[n-i]; isZero=false; } else { answer=answer+num[b.charAt(i)-'0']+unit[n-i]; } } return answer; } public String devideByHM(String a) { String answer=""; if(a.length()>8) { answer=answer+ devideByTS(a.substring(0,a.length()-8))+"億"; if(a.substring(a.length()-8,a.length()).charAt(0)=='0')isZero=true; answer=answer+ devideByTS(a.substring(a.length()-8,a.length())); } else { answer=answer+ devideByTS(a); } return answer; } public String devideByTS(String a) { String answer=""; if(a.length()>4&&!allZero(a.substring(0,a.length()-4))) { answer=answer+ devideByThousand(a.substring(0,a.length()-4))+"萬"; if(a.substring(a.length()-4,a.length()).charAt(0)=='0')isZero=true; answer=answer+ devideByThousand(a.substring(a.length()-4,a.length())); } else { answer=answer+ devideByThousand(a.substring(/*a.length()-4*/0,a.length())); } return answer; } public String devideByThousand(String a) { String answer=""; int unitStart=3; int unitEnd=6; for(int i=0;unitEnd-i>=unitStart&&i<a.length();i++) { if(a.charAt(i)=='0') { isZero=true; continue; } if(isZero) { answer=answer+num[0]+num[a.charAt(i)-'0']+unit[unitStart-1+a.length()-i]; isZero=false; } else { answer=answer+num[a.charAt(i)-'0']+unit[unitStart-1+a.length()-i]; } } return answer; } private boolean allZero(String a) { for(int i=0;i<a.length();i++) { if(a.charAt(i)!='0')return false; } return true; } public void show() { System.out.println(divideByInteger()); } }