1. 程式人生 > >java版,實現人民幣的大小寫轉換

java版,實現人民幣的大小寫轉換

package suanfa;


import java.util.Scanner;


public class Numberconvert {
public static void main(String[] args) {
boolean flag = true;
Scanner sc = new Scanner(System.in);
ConvertChinese convertChinese = new ConvertChinese();
while (flag) {
System.out.println("輸入你要轉換的金額:");
double number = sc.nextDouble();
if (number > 0) {
System.out.println(convertChinese.getChinese(number) + "整");
} else {
flag = false;
}
}
System.out.println("結束,要想測試,請重新執行");
}


}


class ConvertChinese {
private String chinese = "";
private String decimalsChinese = "";
private String intNumber = "";
private String decimals = "";
String chineseUnit = "元=十=百=千=萬=十=百=千=億=十=百=千=萬";
String chineseValue = "零壹貳叄肆伍陸柒捌玖";


public String getChinese(double number) {
// 判斷所傳過來的值,是整數還是小數
String srcNumber = number + "";// 把長整型轉換為String 型
System.out.println("源資料:" + srcNumber);


intNumber = srcNumber.substring(0, srcNumber.indexOf("."));
decimals = srcNumber.substring(srcNumber.indexOf(".") + 1, srcNumber.length());


System.out.println("整數部分:" + intNumber);
System.out.println("小數部分:" + decimals);


String chineseUnit1[] = chineseUnit.split("=");
// 轉換整數部分
for (int i = 0; i < intNumber.length(); i++) {
chinese += chineseValue.charAt(Integer.parseInt(srcNumber.charAt(i) + ""))
+ chineseUnit1[intNumber.length() - 1 - i];
}

boolean isZero=Integer.parseInt(decimals.substring(0,1))==0;
//這個地方的判斷主要是因為,零錢有小數部分,小數部分的預設值是0.0,預設的有小數部分。所以需要判斷
//小數部分那個小數是否為0,如果為0,就需要轉換小數部分了。
// 計算小數部分
if (!(decimals.length() == 1 &&  isZero)) {
decimalsChinese += chineseValue.charAt(Integer.parseInt(decimals.substring(0, 1))) + "角"
+ chineseValue.charAt(Integer.parseInt(decimals.substring(1, 2))) + "分";
}
chinese += decimalsChinese;


while (chinese.indexOf("零零") != -1 || chinese.indexOf("零萬") != -1 || chinese.indexOf("零億") != -1
|| chinese.indexOf("億萬") != -1 || chinese.indexOf("零百") != -1 || chinese.indexOf("零元") != -1
|| chinese.indexOf("零十") != -1 || chinese.indexOf("零千") != -1 || chinese.indexOf("零角") != -1) {
chinese = chinese.replaceAll("零零", "零");
chinese = chinese.replaceAll("零十", "零");
chinese = chinese.replaceAll("零萬", "萬");
chinese = chinese.replaceAll("零億", "億");
chinese = chinese.replaceAll("零元", "元");
chinese = chinese.replaceAll("億萬", "億零");
chinese = chinese.replaceAll("零百", "零");
chinese = chinese.replaceAll("零千", "零");
chinese = chinese.replaceAll("零角", "零");
chinese = chinese.replaceAll("零([十百千])", "零");
}


return chinese;


}
}