Hi! Can someone explain to me this set of codes? i've been converting numbers to roman numerals using those codes, but I don't quite get it, or maybe something is wrong with the codes?

 Private Function FormatRoman(ByVal n As Integer) As String
      If n = 0 Then FormatRoman = "0" : Exit Function
      ' there is no Roman symbol for 0, but we don't want to return an empty string
      Const r = "IVXLCDM" ' Roman symbols
      Dim i As Integer = Math.Abs(n)
      Dim s As String = ""

      For p As Integer = 1 To 5 Step 2
         Dim d As Integer = i Mod 10
         i = i \ 10
         Select Case d ' format a decimal digit
            Case 0 To 3 : s = s.PadLeft(d + Len(s), Mid(r, p, 1))
            Case 4 : s = Mid(r, p, 2) & s
            Case 5 To 8 : s = Mid(r, p + 1, 1) & s.PadLeft(d - 5 + Len(s), Mid(r, p, 1))
            Case 9 : s = Mid(r, p, 1) & Mid(r, p + 2, 1) & s
         End Select
      Next

      s = s.PadLeft(i + Len(s), "M") ' format thousands
      If n < 0 Then s = "-" & s ' insert sign if negative (non-standard)
      FormatRoman = s
   End Function

Thanks

Recommended Answers

All 2 Replies

or maybe something is wrong with the codes?

I don't know. Is there something wrong with the code? Have you tested it?

What arn't you understanding exactly? Do you not get the pattern? Do you not understand roman numerals? Is there something specific about the code that you don't understand?

Out of the input number n, a string s is constructed out of the string "IVXLCDM", using the Mid function.
I have not tested if this is correctly done. Try it out!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.