Is there a way in Java to convert an integer to its ordinal name?

Viewed 42122

I want to take an integer and get its ordinal, i.e.:

1 -> "First"
2 -> "Second"
3 -> "Third"
...
13 Answers
static String getOrdinal(int input) {
    if(input<=0) {
        throw new IllegalArgumentException("Number must be > 0");
    }
    int lastDigit = input % 10;
    int lastTwoDigit = input % 100;
    if(lastTwoDigit >= 10 && lastTwoDigit <= 20) {
        return input+"th";
    }
    switch (lastDigit) {
    case 1:
        return input+"st";
    case 2:
        return input+"nd";
    case 3:
        return input+"rd";

    default:
        return input+"th";
    }
}

Just incase if somone looking for a Kotlin extension version :


fun Int.toEnOrdinal(): String {
    val suffixes = arrayListOf("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")
    return when (this % 100) {
        11, 12, 13 -> "{$this}th"
        else -> "$this" + suffixes[this % 10]
    }
}

then all you need to do is to call this function on any number like

5.toUKOrdinal() --> 5th

21.toUKOrdinal() --> 21st

etc

public static String getOrdinalFor(int value) {
         int tenRemainder = value % 10;
         switch (tenRemainder) {
          case 1:
           return value+"st";
          case 2:
           return value+"nd";
          case 3:
           return value+"rd";
          default:
           return value+"th";
         }
        }
Related