Monday, April 21, 2014

C# number to words

public string ConvertToWords(int Amount)
{
    string words = "";
    var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", 
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
    var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
    
    if (Amount == 0)
        return "zero";

    if (Amount < 0)
        return "minus " + ConvertToWords(Math.Abs(Amount));            

   
    if ((Amount / 10000000) > 0)
    {
        words += ConvertToWords(Amount / 10000000) + " crore ";
        Amount %= 10000000;
    }

    if ((Amount / 100000) > 0)
    {
        words += ConvertToWords(Amount / 100000) + " lakh ";
        Amount %= 100000;
    }           

    if ((Amount / 1000) > 0)
    {
        words += ConvertToWords(Amount / 1000) + " thousand ";
        Amount %= 1000;
    }

    if ((Amount / 100) > 0)
    {
        words += ConvertToWords(Amount / 100) + " hundred ";
        Amount %= 100;
    }

    if (Amount > 0)
    {
        if (words != "")
            words += "and ";
        

        if (Amount < 20)
            words += unitsMap[Amount];
        else
        {
            words += tensMap[Amount / 10];
            if ((Amount % 10) > 0)
                words += " " + unitsMap[Amount % 10];
        }
    }
    return words;
}

No comments:

Post a Comment