MapleCheng

在浩瀚的網路世界中無限潛水欸少年郎!

0%

C# 將數字轉換為英文金額

本文大部分轉自炎龍牙大大,我有根據我所需求的格式稍微地變更了一些。主要是之後改報表會需要用到,所以記錄在自己的文章中。

原文: https://dotblogs.com.tw/dragoncancer/2020/03/03/170546

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class NumberToEnglish
{
public string Number2English(string nu)
{
string dollars = "";
string cents = "";
string tp = "";
string[] temp;
string[] tx = { "", "thousand ", "million ", "billion ", "trillion " };

if (decimal.Parse(nu) == 0) return "Zero Dollars";

else if (decimal.Parse(nu) <= 0) return "Error!! ";

else if(nu.Split('.').Length > 1)
{ //處理小數點(通常是兩位)
temp = nu.Split('.');
string strx = temp[1].ToString();

string cent = GetEnglish(strx);
if (!cent.Equals("")) cents = "point" + cent;
}

//處理整數部分
//先將資料格式化,只取出整數
decimal x = Math.Truncate(decimal.Parse(nu));
//格式化整數部分
temp = x.ToString("#,0").Split(',');
//利用整數,號檢查千、萬、百萬....
int j = temp.Length -1 ;

for (int i = 0; i < temp.Length; i++)
{
tp = tp + GetEnglish(temp[i]);
if (tp != "")
{
tp = tp + tx[j] + "" ;
}
else
{
tp = tp + "";
}

j = j - 1;
}
if (x == 0 && cents != "") // 如果整數部位= 0 ,且有小數
{
dollars = "Zero Dollars And" + cents + " only";
}
else
{
if (cents == "")
{
dollars = tp + "dollars only";
}
else
{
dollars = tp + cents + "only";
}
}
return dollars;
}

private string GetEnglish(string nu)
{
string x = "";
string str1;
string str2;
string[] tr = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
string[] ty = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

//處理百位數
str1 = tr[int.Parse(nu) / 100] + " hundred"; //EX 當315除以100 用於int 會取出3 ..對應到字串陣列,就是 Three
if (str1.Equals(" hundred")) str1 = ""; //如果結果是空值,表示沒有百分位
//處理十位數
int temp = int.Parse(nu) % 100; // 當315 除100 會剩餘 15

if (temp < 20)
{
str2 = tr[temp]; //取字串陣列
}
else
{
str2 = ty[(temp / 10)].ToString(); //十位數 10/20/30的數量確認

if (str2.Equals(""))
{
str2 = tr[(temp % 10)] ;
}
else if((temp % 10) > 0)
{
str2 = str2 + "-" + tr[(temp % 10)] ; //十位數組成
}

}
if (str1 == "" && str2 == "")
{
x = "";
}
else
{
x = str1 + " " + str2 + " " ;
}

return x;
}
}