How to Generate Roman Numerals
One
thing you get when you work with a customer base as wide as the one we have at
our company is a list of useful scripts. As no two customers want the exact
same thing, these little scripts come in handy.
Here is one that I have that changes an Integer into a Roman Numeral.
Let's show some code first:
private string
ConvertToRoman(int Value)
{
System.Text.StringBuilder sbRN = new
System.Text.StringBuilder();
//Start
high, and just replace the huge numbers with letters.
// 1111
-> M111 -> MC11 ->MCX1 -> MCXI
sbRN.Append(GenerateNumber(ref Value, 1000, 'M'));
sbRN.Append(GenerateNumber(ref Value, 500, 'D'));
sbRN.Append(GenerateNumber(ref Value, 100, 'C'));
sbRN.Append(GenerateNumber(ref Value, 50, 'L'));
sbRN.Append(GenerateNumber(ref Value, 10, 'X'));
sbRN.Append(GenerateNumber(ref Value, 5, 'V'));
sbRN.Append(GenerateNumber(ref Value, 1, 'I'));
//let's replace the some substrings like:
//IIII to
IV, VIV to IX, etc.
sbRN.Replace("IIII", "IV");
sbRN.Replace("VIV", "IX");
sbRN.Replace("XXXX", "XL");
sbRN.Replace("LXL", "XC");
sbRN.Replace("CCCC", "CD");
sbRN.Replace("DCD", "CM");
return (sbRN.ToString());
}
private string
GenerateNumber(ref int
value, int magnitude, char
letter)
{
System.Text.StringBuilder sbNumberString = new System.Text.StringBuilder();
while (value >= magnitude)
{
value -= magnitude;
sbNumberString.Append(letter);
}
return (sbNumberString.ToString());
}
Roman Numerals are pretty
straight forward once you get used to it. When you start with a number, say
1234, you will want the roman numeral: MCCXXXIV.
What this above script will
do is take in the 1000, set M to the letter to be returned, and take 1000
off of the Value (Passed by Reference). It will then take the 200 and return
CC, the 30 return XXX and the 4 which will return IIII. The IIII is then turned
into IV.
Pretty easy script to use, and helpful if you ever need to produce Roman Numerals.