2015-06-29 2 views
-2

Мой код преобразует только полные числа в пределах (1-9999). Мне нужно преобразовать все числа, и если число (например, 2564866258) содержит центы (например, 1928.25), которые должны быть преобразованы в слова. Ниже мой код. Может ли кто-нибудь помочь мне решить эту проблему.преобразование всех чисел, включая центы, в слово

private void amt_txt_KeyUp(object sender, KeyEventArgs e) 
     { 
      string[] Ones = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Ninteen" }; 

      string[] Tens = { "Ten", "Twenty", "Thirty", "Fourty", "Fift", "Sixty", "Seventy", "Eighty", "Ninty" }; 

      int no = int.Parse(amt_txt.Text); 
      string strWords = ""; 

      if (no > 999 && no < 10000) 
      { 
       int i = no/1000; 
       strWords = strWords + Ones[i - 1] + " Thousand "; 
       no = no % 1000; 
      } 

      if (no > 99 && no < 1000) 
      { 
       int i = no/100; 
       strWords = strWords + Ones[i - 1] + " Hundred "; 
       no = no % 100; 
      } 

      if (no > 19 && no < 100) 
      { 
       int i = no/10; 
       strWords = strWords + Tens[i - 1] + " "; 
       no = no % 10; 
      } 

      if (no > 0 && no < 20) 
      { 
       strWords = strWords + Ones[no - 1]; 
      } 

      cnv_txt.Text = strWords; 

     } 
+4

и ваша проблема ...? –

+0

@MarcB Code работает. Мне нужен этот код для преобразования большого количества. Его единственное преобразование до 9999. и не может преобразовать, если число содержит точку (например: 125.50) –

+0

Я не вижу проблемы с большими числами, вам просто нужно поставить больше условий. и для десятичной части вы можете добавить условие «положить» и «в свою строку –

ответ

2

Это тот конвертер, который вам нужен. Использование методов снижает сложность вашего кода.

Этот алгоритм преобразует число в такие слова.

Входной сигнал: "1234567"

  1. Получите 3 последние цифры. "567"

  2. Преобразуйте его в слова. Пятьсот шестьдесят семь

  3. Применить свой разделитель. Пятьсот шестьдесят семь (Там нет разделителя 3 последних цифр)

  4. Повтор: Получите 3 последние цифры «234»

  5. Преобразование его слов. Две сотни тридцать четыре

  6. Применить свой разделитель. Двести тридцать четыре тысячи

  7. Append к Resault.Two Сто тридцать четыре тысячи пятьсот шестьдесят семь

  8. Repeat: Получите 3 последние цифры. "1" (Осталось только одна цифра)

  9. Преобразуйте его в слова. Один

  10. Применить его разделитель. Один миллион

  11. Append до Resault.One миллиона двести тридцать четыре тысячи пятьсот шестьдесят семь

Готово.

Я прокомментировал код, если он поможет.

Если вы не понимаете некоторые детали, просто спросите, не объясните.

Также для Десятимов мы их разделяем, преобразуем их в слова. наконец, добавим их к результату в конце.

private static void Main(string[] args) 
    { 

     string input = "123466265.123"; 

     // take decimal part of input. convert it to word. add it at the end of method. 
     string decimals = ""; 

     if (input.Contains(".")) 
     { 
      decimals = input.Substring(input.IndexOf(".") + 1); 
      // remove decimal part from input 
      input = input.Remove(input.IndexOf(".")); 
     } 

     // Convert input into words. save it into strWords 
     string strWords = GetWords(input); 


     if (decimals.Length > 0) 
     { 
      // if there is any decimal part convert it to words and add it to strWords. 
      strWords += " Point " + GetWords(decimals); 
     } 

     Console.WriteLine(strWords); 
    } 

    private static string GetWords(string input) 
    { 
     // these are seperators for each 3 digit in numbers. you can add more if you want convert beigger numbers. 
     string[] seperators = { "", " Thousand ", " Million ", " Billion " }; 

     // Counter is indexer for seperators. each 3 digit converted this will count. 
     int i = 0; 

     string strWords = ""; 

     while (input.Length > 0) 
     { 
      // get the 3 last numbers from input and store it. if there is not 3 numbers just use take it. 
      string _3digits = input.Length < 3 ? input : input.Substring(input.Length - 3); 
      // remove the 3 last digits from input. if there is not 3 numbers just remove it. 
      input = input.Length < 3 ? "" : input.Remove(input.Length - 3); 

      int no = int.Parse(_3digits); 
      // Convert 3 digit number into words. 
      _3digits = GetWord(no); 

      // apply the seperator. 
      _3digits += seperators[i]; 
      // since we are getting numbers from right to left then we must append resault to strWords like this. 
      strWords = _3digits + strWords; 

      // 3 digits converted. count and go for next 3 digits 
      i++; 
     } 
     return strWords; 
    } 

    // your method just to convert 3digit number into words. 
    private static string GetWord(int no) 
    { 
     string[] Ones = 
     { 
      "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", 
      "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Ninteen" 
     }; 

     string[] Tens = {"Ten", "Twenty", "Thirty", "Fourty", "Fift", "Sixty", "Seventy", "Eighty", "Ninty"}; 

     string word = ""; 

     if (no > 99 && no < 1000) 
     { 
      int i = no/100; 
      word = word + Ones[i - 1] + " Hundred "; 
      no = no%100; 
     } 

     if (no > 19 && no < 100) 
     { 
      int i = no/10; 
      word = word + Tens[i - 1] + " "; 
      no = no%10; 
     } 

     if (no > 0 && no < 20) 
     { 
      word = word + Ones[no - 1]; 
     } 

     return word; 
    } 
Смежные вопросы