Android Conversion to Ordinal Format

Just for future reference, I came across this issue and discovered that now you can use the ICU MessageFormat to do something like this:

import android.icu.text.MessageFormat

fun toOrdinal(day: String): String {
    val formatter = MessageFormat("{0,ordinal}", Locale.getDefault())
    return formatter.format(arrayOf(day.toInt()))
}

You will get these results:

1 -> 1st
2 -> 2nd
3 -> 3rd
4 -> 4th
5 -> (...)

Java nor Android have support for creating ordinal strings. Android does have support for creating plural string resources, but not ordinals.


If the range for which you need ordinals is limited, then you are probably best to use a <string-array> to define them:

<string-array name="ordinals">
  <item>zeroth</item>
  <item>1st</item>
  <item>2nd</item>
  <item>3rd</item>
  <item>4th</item>
  <item>5th</item>
  <item>6th</item>
</string-array>

and then access it via:

String ordinal = getResources().getStringArray(R.array.ordinals)[count];

Of course this doesn't get you automatic translation into other languages - you have to do that yourself (and if your count goes outside the range in this simplistic code you will get an exception).

Tags:

Android