Page 1 of 2

How to generate an ordinal number

Posted: Saturday 10th July 2021 9:25am
by bill-lancaster
Is there an available method to convert say "5" to "5th" or "23" to "23rd"?

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 11:15am
by bill-lancaster
Since I'm looking at day values of a date,
Select Case day_number MOD 10
Case 1
st
Case 2
nd
Case 3
rd
Case else
th
End Select

I guess this will do it, a bit messy though

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 11:18am
by BruceSteers
No, 5 is Integer, 5th is String.
It's a simple function...

Public nth(v as integer, Textonly as Boolean)
Dim s as string =iif(textonly,"",str(v))
Dim n as Integer = v ٪ 10

Select n
Case 1
S &= "st"
Case 2
S &= "nd"
Case 3
S &= "rd"
Case else
S &= "th"
Return s
End

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 11:24am
by BruceSteers
Not so dirty...

Dim ss as string[] = ["th","st","nd","rd","th"]
Dim v as Integer = value % 10
Return Str(value) & ss[Min(v,4)]

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 11:51am
by cogier
Here is my version: -
Public Sub Form_Open()

  Dim dDate As Date = Date(Now)
  Dim sOrdinal As String = GetOrdinal(Format(dDate, "dd"))

  Print Format(dDate, "dddd d") & sOrdinal & Format(dDate, " mmmm yyyy")

End

Public Sub GetOrdinal(sDay As String) As String

  Dim iDay As Integer = Val(sDay)
  Dim sOrdinal As String = "th"

  Select Case iDay
    Case 1, 21, 31
      sOrdinal = "st"
    Case 2, 22
      sOrdinal = "nd"
    Case 3, 23
      sOrdinal = "rd"
  End Select

  Return sOrdinal

End
The result for today is Saturday 10th July 2021

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 11:58am
by bill-lancaster
I like the not so dirty solution, thanks Bruce and Cogier.

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 12:45pm
by grayghost4
I like Cogier's solution very well done ;)

I can tell you have been reading " 'Clean Code' by Robert C. Martin "

I think everyone should read that book

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 1:00pm
by cogier
I like Cogier's solution very well done ;)

I can tell you have been reading " 'Clean Code' by Robert C. Martin "

I think everyone should read that book
Thanks for the kind words, but I have never read that book!

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 1:05pm
by grayghost4

Re: How to generate an ordinal number

Posted: Saturday 10th July 2021 2:16pm
by BruceSteers
I like shorter, as short as can be is best for me...
I got it to a one liner 🙂

Public Sub GetOrdinal(v as Integer) As String
Return(["th","st","nd","rd","th"][Min(4, v % 10)])
End

Not sure if defining a string[] ad-hoc like that works though (cant test as am at work)
😉