Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localized Ordinal Numbers in Java

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?

like image 662
laptou Avatar asked Jun 14 '26 08:06

laptou


2 Answers

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.º"
like image 163
Westy92 Avatar answered Jun 15 '26 21:06

Westy92


International Components for Unicode (ICU)

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);
like image 41
Yetispapa Avatar answered Jun 15 '26 22:06

Yetispapa