.NET Technical bits: 2012

Friday, June 15, 2012

Convert number to words using C#

Convert number to words using C#

static string[] ones ={"", "one" , "two", "three", "four", "five", "six", "seven", "eight" , "nine", "ten" ,
"eleven", "twelve" , "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};




static string[] tens ={"zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};



static string[] thou = { "", "thousand", "lakh"};

public static string NumberToWords(int inputNum)

{

int dig1, dig2, dig3, level = 0, lasttwo, threeDigits;

string retval = "";

string x = "";

try

{

bool isNegative = false;

if (inputNum < 0)

{

isNegative = true;

inputNum *= -1;

}



if (inputNum == 0)

return ("ZERO");



string s = inputNum.ToString();



while (s.Length > 0)

{

// Get the three rightmost characters

x = (s.Length < 3) ? s : s.Substring(s.Length - 3, 3);



// Separate the three digits

threeDigits = int.Parse(x);

lasttwo = threeDigits % 100;

dig1 = threeDigits / 100;

dig2 = lasttwo / 10;

dig3 = (threeDigits % 10);



// append a "thousand" where appropriate

if (level > 0 && dig1 + dig2 + dig3 > 0)

{

retval = thou[level] + " " + retval;

retval = retval.Trim();

}



// check that the last two digits is not a zero

if (lasttwo > 0)

{

if (lasttwo < 20) // if less than 20, use "ones" only

retval = ones[lasttwo] + " " + retval;

else // otherwise, use both "tens" and "ones" array

retval = tens[dig2] + " " + ones[dig3] + " " + retval;

}



//Lakhs

if (level > 0 && dig1 > 0)

{

if (dig1 > 1)

{

retval = ones[dig1] + " lakhs " + retval;

}

else

{

retval = ones[dig1] + " lakh " + retval;

}

}// if a hundreds part is there, translate it

else if (dig1 > 0)

retval = ones[dig1] + " hundred " + retval;



s = (s.Length - 3) > 0 ? s.Substring(0, s.Length - 3) : "";

level++;

}



while (retval.IndexOf(" ") > 0)

retval = retval.Replace(" ", " ");



retval = retval.Trim();



if (isNegative)

retval = "negative " + retval;

}

catch (Exception)

{

}

return (retval);

}