你需要转换的数字比较大,100以内的,不能全凭手写,我给你写一个静态类,作为工具类吧。能够装换所有的数字。- public static class NumToStr
- {
- private static readonly string MINUS = "minus";
- private static readonly string[] X_TEN =
- {
- "one", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred"
- };
- private static readonly string[] DIGIT_STR = { "", "thousand", "million", "billion" };
- private static readonly int[] DIGIT_NUM = { 1, 1000, 1000000, 1000000000 };
- private static readonly string[] BASE =
- {
- "zero","one","two","three","four","five","six","seven","eight","nine","ten",
- "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"
- };
- private static string LessThan1000(int num)
- {
- String result = "";
- Lable_Begin:
- if (num < 21)
- {
- result += BASE[num];
- }
- else if (num < 100)
- {
- result += X_TEN[num / 10];
- if ((num %= 10) != 0)
- {
- result += "-";
- goto Lable_Begin;
- }
- }
- else
- {
- result += BASE[num / 100] + " " + X_TEN[10];
- if ((num %= 100) != 0)
- {
- result += " and ";
- goto Lable_Begin;
- }
- }
- return result;
- }
- public static string Convert(int num)
- {
- if (num == 0) return BASE[0];
- int abs = Math.Abs(num);
- StringBuilder result = new StringBuilder(16);
- for (int i = DIGIT_NUM.Length - 1; i > -1; i--)
- {
- int l = abs / DIGIT_NUM[i];
- if (l > 0)
- {
- if (result.Length > 0) result.Append(' ');
- result.Append(LessThan1000(l));
- if (DIGIT_STR[i] != String.Empty) result.Append(' ');
- result.Append(DIGIT_STR[i]);
- }
- abs %= DIGIT_NUM[i];
- }
- return (num < 0 ? MINUS + " " : "") + result.ToString();
- }
- }
复制代码 |