Number to String conversion

Hi,
Generally in finance or banking or this kind of requirement is needed. Its more or less a common thing to convert a number to a string. I used this to convert currency to words format.

Here is the snippet.

/// 
/// Numbers to text.
/// 
/// The value.
/// 
public string NumberToText(int value)
{
 string[] num0to10 = new string[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
 string[] num11to20 = new string[] { "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty" };
 string[] num20to100 = new string[] { "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Twenty" };

 string result = string.Empty;

 int INumValue;
 int ThousValue;
 int HundsValue;
 int TensValue;
 int OnesValue;
 int TeenChk;

 OnesValue = 0;
 INumValue = value;

 if (INumValue == 0)
 {
  result = "Zero";
 }
 else
 {
  ThousValue = (INumValue / 1000);
  if (ThousValue > 0)
   INumValue = INumValue - (ThousValue * 1000);

  HundsValue = (INumValue / 100);
  if (HundsValue > 0)
   INumValue = INumValue - (HundsValue * 100);

  TeenChk = INumValue;

  if (INumValue >= 20)
  {
   TensValue = (INumValue / 10);
   if (TensValue > 0)
   {
    INumValue = INumValue - (TensValue * 10);
   }
   OnesValue = INumValue;
  }
  else
  {
   TensValue = INumValue;
  }

  if (ThousValue > 0)
  {
   result = num0to10[ThousValue] + " Thousand";
   if (HundsValue == 0)
    result = result + " and ";
  }

  if (HundsValue > 0)
  {
   result = result + " " + num0to10[HundsValue] + " Hundred";
   if (TensValue > 0 || OnesValue > 0)
    result = result + " and ";
  }

  if (TensValue > 0)

   if (TeenChk < 20)

    if (TeenChk <= 10)

     result = result + num0to10[TeenChk];
    else
     result = result + num11to20[TeenChk - 11];
   else
    result = result + ' ' + num20to100[TensValue - 1];
  if (OnesValue > 0)
   result = result + ' ' + num0to10[OnesValue];
 }

 return result.Trim();
}


Hope it helps anyone of you.

Regrads,
Pavan N

Comments

Popular posts from this blog

Download file using WCF REST services

server side printing / PDF conversions using c# and asp.net/wcf service

Finding file size in bytes on serverside using c#