Monday, June 3, 2013

How to convert Numeric values into Roman numbers

The simple way for converting numeric values to Roman numbers :

public static string NumberToRoman(int number)
        {
            //taking string builder here, so we can append roman numbers to this string builder
            StringBuilder result = new StringBuilder();
            if (number <= 0 || number > 3999)
            {
                //throw new ArgumentException("Value must be in the range 0 – 3,999.");
                Console.WriteLine("Value must be in the range 0 to 3,999....!");
                Console.ReadLine();
            }
            else
            {
                int[] values = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
                string[] numerals = new string[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };

                // Loop through each of the values to diminish the number
                for (int i = 0; i < values.Length; i++)
                {
                    // If the number being converted is less than the test value, append the corresponding numeral or numeral pair to the resultant string(string builder)
                    while (number >= values[i])
                    {
                        number -= values[i];
                        result.Append(numerals[i]);
                    }
                }
                Console.WriteLine(result);
                Console.ReadLine();              
            }
            return result.ToString();
        }

No comments:

Post a Comment