瘋狂JAVA習題 數字轉換成人民幣

public class Num2Rmb{
private String[] hanArr = {"零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"};
private String[] unitArr = {"", "十", "佰", "仟"};
private String[] four_uinitArr = {"", "萬", "億"};
private String[] two_unitArr = {"角", "分"};

private String[] divide(double num)
{
String[] result = new String[2];

long iValue = (long)num;
int fValue = (int)((num - iValue)*100);

result[0] = ""+ iValue;
result[1] = ""+ fValue;
System.out.println("整數:" + result[0] + ", 小數:" + result[1]);
return result;
}

private String itoHanStr(String numstr)
{
int len = numstr.length();
int col = (len-1)/4;
int row = (len-1) % 4;
String result = "";
int index = 0;

if(len > 12)
{
System.out.println("too big, please enter again: \n");
return null;
}
System.out.println("col = " + col + ", row = " + row);
for(int i = 0; i <= col; i++)
{
for(int j = 0; j <= row; j++)
{
if(numstr.charAt(index) == '0')
{
if((numstr.charAt(index-1) == '0' && j != 0)|| j == row) 
{
index++;
continue;
}
result += hanArr[numstr.charAt(index) - '0'];
}
else
{
result += hanArr[numstr.charAt(index) - '0'];
result += unitArr[row-j];
}
index++;
}
result += four_uinitArr[col-i];
row = 3;
}

return result;
}
private String ftoHanStr(String numstr)
{
String result = "";

if(numstr == "00")
return null;
result += hanArr[numstr.charAt(0) - '0'];
if(numstr.charAt(0) != '0')
{
result += two_unitArr[0];
}
result += hanArr[numstr.charAt(1) - '0'];
if(numstr.charAt(1) != '0')
{
result += two_unitArr[1];
}
return result;
}

public static void main(String[] args)
{
Num2Rmb nr = new Num2Rmb();
//123 4567 8903
//1005200436.85
//105342006.85
double d = 1005200436.85;
String[] result = nr.divide(d);

System.out.println(nr.itoHanStr(result[0])+ "元");
System.out.println(nr.ftoHanStr(result[1]));
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章