Tuesday, September 13, 2011

How to convert Roman numerals to Integer in C#

I was looking up the web all day but couldn't find any C# code for converting Roman letters or numerals to Integer value. The best thing i came across was this code by andyb but the problem was it has been written in PHP which I had no clue :)

So I had just taken the logic of AndyB and converted it into C# for anybody who cares for it.

Add this Namespace:

using System.Collections.Generic;

Solution:

Dictionary RomanNumbers =   new Dictionary();
RomanNumbers.Add("M", 1000);
RomanNumbers.Add("CM", 900);
RomanNumbers.Add("D", 500);
RomanNumbers.Add("CD", 400);
RomanNumbers.Add("C", 100);
RomanNumbers.Add("XC", 90);
RomanNumbers.Add("L", 50);
RomanNumbers.Add("XL", 40);
RomanNumbers.Add("X", 10);
RomanNumbers.Add("IX", 9);
RomanNumbers.Add("V", 5);
RomanNumbers.Add("IV", 4);
RomanNumbers.Add("I", 1);


string strRomanValue = "MCMLXXVI";
int result = 0;


foreach (KeyValuePair pair in RomanNumbers )
{
    while (strRomanValue.IndexOf(pair.Key.ToString()) == 0)
     {
           result += int.Parse(pair.Value.ToString());
           strRomanValue = strRomanValue.Substring(pair.Key.ToString().Length);
     }
}
Response.Write(result.ToString());

1 comment:

the searcher said...

Here's the C# function for VS 2010:
public static int ConvertRomanNumtoInt(string strRomanValue)
{
Dictionary RomanNumbers = new Dictionary
{
{"M", 1000},
{"CM", 900},
{"D", 500},
{"CD", 400},
{"C", 100},
{"XC", 90},
{"L", 50},
{"XL", 40},
{"X", 10},
{"IX", 9},
{"V", 5},
{"IV", 4},
{"I", 1}
};
int retVal = 0;
foreach (KeyValuePair pair in RomanNumbers)
{
while (strRomanValue.IndexOf(pair.Key.ToString()) == 0)
{
retVal += int.Parse(pair.Value.ToString());
strRomanValue = strRomanValue.Substring(pair.Key.ToString().Length);
}
}
return retVal;

}