Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - Format numbers to roman numerals?

Is it possible to use Format function to display integers in roman numerals?

For Counter As Integer = 1 To 10
   Literal1.Text &= Format(Counter, "???")
Next
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is what I found on http://www.source-code.biz/snippets/vbasic/7.htm

(originally written by Mr Christian d'Heureuse in VB)

I converted it to VB.net:

   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

I hope this will help others.

Cheers - Dave.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...