C code instance that converts a number to a capital amount
- 2020-06-23 01:43:25
- OfStack
Implementation code:
// Such as: (new Money(200)).ToString() == " ErBai yuan "
namespace Skyiv.Util {
using System.Text;
class Test {
static void Main() {
for (;;) {
System.Console.Write(" The amount of : ");
string s = System.Console.ReadLine();
decimal m;
try {
m = decimal.Parse(s);
} catch {
break;
}
System.Console.WriteLine(" A capital : " + new Money(m));
}
}
}
// Class overloaded ToString() Method returns an uppercase amount string
class Money {
public string Yuan = " yuan "; // "Yuan" can be changed to "yuan", "ruble" and so on
public string Jiao = " Angle "; // "Angle", you can change it to "pick up".
public string Fen = " points "; // "Cents" can be changed to something like "cents"
static string Digit = " One twenty-three fifty-seven nine "; // Upper case number
bool isAllZero = true; // Whether the segment is zero
bool isPreZero = true; // low 1 Whether the digit is zero
bool Overflow = false; // Overflow mark
long money100; // The amount of *100 , the amount in "cents"
long value; // money100 The absolute value of
StringBuilder sb = new StringBuilder(); // Uppercase amount string, in reverse order
// Read-only property : " Zero yuan "
public string ZeroString {
get {
return Digit[0] + Yuan;
}
}
// The constructor
public Money(decimal money) {
try {
money100 = (long)(money * 100m);
} catch {
Overflow = true;
}
if (money100 == long.MinValue) Overflow = true;
}
// overloading ToString() Method, which returns an uppercase amount string
public override string ToString() {
if (Overflow) return " Amount out of range ";
if (money100 == 0) return ZeroString;
string[] Unit = {
Yuan,
" wan ",
" Hundred million ",
" wan ",
" One hundred million "
};
value = System.Math.Abs(money100);
ParseSection(true);
for (int i = 0; i < Unit.Length && value > 0; i++) {
if (isPreZero && !isAllZero) sb.Append(Digit[0]);
if (i == 4 && sb.ToString().EndsWith(Unit[2])) sb.Remove(sb.Length - Unit[2].Length, Unit[2].Length);
sb.Append(Unit[i]);
ParseSection(false);
if ((i % 2) == 1 && isAllZero) sb.Remove(sb.Length - Unit[i].Length, Unit[i].Length);
}
if (money100 < 0) sb.Append(" negative ");
return Reverse();
}
// Parse "Fragments" : "Angle points (2 position ) "Or" Within ten thousand 1 Period of (4 position ) "
void ParseSection(bool isJiaoFen) {
string[] Unit = isJiaoFen ? new string[] {
Fen,
Jiao
}: new string[] {
"",
" Pick up ",
" hk ",
" micky "
};
isAllZero = true;
for (int i = 0; i < Unit.Length && value > 0; i++) {
int d = (int)(value % 10);
if (d != 0) {
if (isPreZero && !isAllZero) sb.Append(Digit[0]);
sb.AppendFormat("{0}{1}", Unit[i], Digit[d]);
isAllZero = false;
}
isPreZero = (d == 0);
value /= 10;
}
}
// Reverse string
string Reverse() {
StringBuilder sbReversed = new StringBuilder();
for (int i = sb.Length - 1; i >= 0; i--) sbReversed.Append(sb[i]);
return sbReversed.ToString();
}
}
}