Mega Code Archive

 
Categories / C# / Data Types
 

Converts an integer into a roman numeral

//http://advancementvoyage.codeplex.com/ //Microsoft Public License (Ms-PL) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AdvancementVoyage.Magic.Utility {     /// <summary>     /// Extension methods for the int type.     /// </summary>     public static class IntExtensions     {         /// <summary>         /// Converts an integer into a roman numeral.         /// </summary>         /// <param name="number">         /// The number being transformed.         /// </param>         /// <returns>         /// A string representation of the number's corresponding roman numeral.         /// </returns>         public static string ToRomanNumeral(this int number)         {             var retVal = new StringBuilder(5);             var valueMap = new SortedDictionary<int, string>                                {                                    { 1, "I" },                                    { 4, "IV" },                                    { 5, "V" },                                    { 9, "IX" },                                    { 10, "X" },                                    { 40, "XL" },                                    { 50, "L" },                                    { 90, "XC" },                                    { 100, "C" },                                    { 400, "CD" },                                    { 500, "D" },                                    { 900, "CM" },                                    { 1000, "M" },                                };             foreach (var kvp in valueMap.Reverse())             {                 while (number >= kvp.Key)                 {                     number -= kvp.Key;                     retVal.Append(kvp.Value);                 }             }             return retVal.ToString();         }     } }