Saturday, 27 August 2011

Number to text



I had to convert number to text and haven't found any nice implemenation in 30 minutes of googling, so I created my own:

using System;
using System.Text.RegularExpressions;

class NumberToText
{
    private static string[] _numbers = { string.Empty, "one", "two", "three",
            "four", "five", "six", "seven", "eight", "nine" };
    private const string _hundred = " hundred";
    private static string[] _numbersT = { "", "ten", "twenty", "thirty",
            "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" };
    private static string[] _numbers11_19 = { "", "eleven", "twelve",
            "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
            "eightteen", "nineteen" };
    private static string _thousand = " thousand ";
    private static string _million = "one million and more";

    private static string _ConvertNumber(uint inputNumber)
    {
        string unitStr, tenStr, tenString;
        uint hundreds = inputNumber / 100;
        uint hundredReminder = inputNumber % 100;
        uint tens = hundredReminder / 10;
        uint units = hundredReminder % 10;

        tenString = _numbers[hundreds < 10 ? hundreds : 0]
                + (hundreds > 0 ? _hundred : string.Empty);
        if (tens == 1 && units != 0)
        {
            tenStr = _numbers11_19[units];
            unitStr = string.Empty;
        }
        else
        {
            tenStr = _numbersT[tens];
            unitStr = _numbers[units];
        }

        return string.Format("{0} {1} {2}", tenString, tenStr, unitStr);
    }

    public static string ConvertNumber(uint inputNumber)
    {
        if (inputNumber < 1000)
            return _ConvertNumber(inputNumber);
        else if (inputNumber < 1000000)
            return _ConvertNumber(inputNumber / 1000) + _thousand
                    + _ConvertNumber(inputNumber % 1000);
        else
            return _million;
    }

    public static string RemoveExtraSpaces(string input)
    {
        return Regex.Replace(input, "\\W+", " ").Trim();
    }

    public static void Main(string[] args)
    {
        for (uint i = 1; i < 2000; i++)
        {
            Console.WriteLine(RemoveExtraSpaces(ConvertNumber(i)));
        }
    }
}

No comments: