Before I go reinventing the wheel, does Android have any facility for converting an integer to an ordinal string with multi-language support? That is, it would convert the integer 3 to "3rd" in English and "3eme" in French.
I can see how to do this myself using a bit of logic along with Android's automatic string substitution, but thought that this surely must have been encountered by others, and not just for use with dates.
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 -> (...)
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).
Java nor Android have support for creating ordinal strings. Android does have support for creating plural string resources, but not ordinals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With