Code to aid in the conversion of standard Roman Numerals (1 - 3,999).
Code:
Public Class RomanNumeral
Enum Roman
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
End Enum
Private Shared Translation As List(Of Roman) = [Enum].GetValues(GetType(Roman)).OfType(Of Roman).OrderByDescending(Function(t) t).ToList
Public Shared Function ToRoman(num As Integer) As String
Dim rv As New System.Text.StringBuilder
For Each t As Roman In Translation
If num <= 0 Then Exit For
While num >= t
num -= t
rv.Append(t.ToString)
End While
Next
Return rv.ToString
End Function
Public Shared Function FromRoman(num As String) As Integer
Dim rv As Integer
For Each t As Roman In Translation
If num = "" Then Exit For
While num.StartsWith(t.ToString)
rv += t
num = num.Remove(0, t.ToString.Length)
End While
Next
Return rv
End Function
Public Shared Function ToXMLTable() As XElement
Dim root As XElement = <RomanNumerals></RomanNumerals>
Dim entry As XElement = <number>
<value></value>
<roman></roman>
</number>
Dim rv As New XElement(root)
For x As Integer = 1 To 3999
Dim ent As New XElement(entry)
ent.<value>.Value = x.ToString
ent.<roman>.Value = ToRoman(x)
rv.Add(ent)
Next
Return rv
End Function
End Class
To test:
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim foo As XElement = RomanNumeral.ToXMLTable
For Each xe As XElement In foo.Elements
Dim r As String = xe.<roman>.Value
Dim rc As Integer = RomanNumeral.FromRoman(r)
Debug.WriteLine("{0,4} {1,-16} {2,4} {3}", xe.<value>.Value, r, rc.ToString, rc.ToString = xe.<value>.Value)
Next
End Sub