4

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. Is there a library or anything that would allow me to dodge having to implement this myself for every language?

laptou
  • 6,389
  • 2
  • 28
  • 59
  • Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. You **might** try your luck at [softwarereqs](https://softwarerecs.stackexchange.com) - but **first** study the corresponding help center to enable yourself to understand the policies of that community. And consider deleting *this* question please! Thanks! – GhostCat Apr 10 '18 at 06:45
  • @GhostCat There are hundreds of questions on StackOverflow that have answers that link to API functions or libraries like Apache Commons. This is what I'm looking for, and I would accept a technique or piece of code just as easily as a 3rd party library. – laptou Apr 10 '18 at 12:49
  • So there are hundreds of questions that don't meet the criteria of this community. Thus that suddenly turn your question on-topic?! I didn't make up these rules. I am merely making you aware of it. And then I gave you an alternative option. And of course, there are always things like reddit, too. – GhostCat Apr 10 '18 at 13:46

2 Answers2

6

add the icu dependency 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);
Yetispapa
  • 2,174
  • 2
  • 30
  • 52
5

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.º"
Westy92
  • 19,087
  • 4
  • 72
  • 54
  • 1
    please note this needs Android >= 7.0 and that you have to be careful to use android.icu.text.MessageFormat, not java.text.MessageFormat – ChristophK Mar 05 '20 at 09:07