Before you flag my question as a duplicate, I have already seen the answers to this question and this question.
The ordinal suffix rules in English are simple enough as those answers demonstrate, but I'm hoping for an approach that supports localization. For example, the ordinal format of 10 is 10th in English, but it's 10.º in Spanish.
How to generate localized text for ordinal numbers?
Here's an Android-specific example that should honor locales. Note that it's written in Kotlin. This requires Android 7.0 or later.
import android.icu.text.MessageFormat // Don't use java.text.MessageFormat!
val value = 123
val formatter = MessageFormat("{0,ordinal}", Locale("es", "ES")) // Locale.US for English
val ordinalValue = formatter.format(arrayOf(value)) // "123.º"
Add the ICU dependency for Java (icu4j) to your Gradle:
implementation 'com.ibm.icu:icu4j:xx.xx'
Now you have the RuleBasedNumberFormat where you can write something like this to achieve the localized ordinal numbers:
RuleBasedNumberFormat formatter = new RuleBasedNumberFormat(Locale.UK, RuleBasedNumberFormat.ORDINAL);
//ordinalNumber = "1st"
String ordinalNumber = formatter.format(1);
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