Numbers To Roman
This algorithm converts decimal numbers to roman numerals.
public static string NumbersToRoman(int num)
{
StringBuilder roman = new StringBuilder();
int totalM = num / 1000;
num %= 1000;
int totalCM = num / 900;
num %= 900;
int totalD = num / 500;
num %= 500;
int totalCD = num / 400;
num %= 400;
int totalC = num / 100;
num %= 100;
int totalXC = num / 90;
num %= 90;
int totalL = num / 50;
num %= 50;
int totalXL = num / 40;
num %= 40;
int totalX = num / 10;
num %= 10;
int totalIX = num / 9;
num %= 9;
int totalV = num / 5;
num %= 5;
int totalIV = num / 4;
num %= 4;
roman.Append(RepeatString("M", totalM));
roman.Append(RepeatString("CM", totalCM));
roman.Append(RepeatString("D", totalD));
roman.Append(RepeatString("CD", totalCD));
roman.Append(RepeatString("C", totalC));
roman.Append(RepeatString("XC", totalXC));
roman.Append(RepeatString("L", totalL));
roman.Append(RepeatString("XL", totalXL));
roman.Append(RepeatString("X", totalX));
roman.Append(RepeatString("IX", totalIX));
roman.Append(RepeatString("V", totalV));
roman.Append(RepeatString("IV", totalIV));
roman.Append(RepeatString("I", num));
return roman.ToString();
}
private static string RepeatString(string s, int count)
{
if (count < 0) return string.Empty;
StringBuilder str = new StringBuilder(count);
for (int i = 0; i < count; ++i)
{
str.Append(s);
}
return str.ToString();
}
Example
int data = 419;
string value = NumbersToRoman(data);
Output
CDXIX