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

后端 未结 12 1308
生来不讨喜
生来不讨喜 2020-11-27 15:12

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

1 -> \"First\"
2 -> \"Second\"
3 -> \"Third\"
...
12条回答
  •  离开以前
    2020-11-27 15:44

    In 1 line:

    public static String ordinal(int i) {
        return i % 100 == 11 || i % 100 == 12 || i % 100 == 13 ? i + "th" : i + new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[i % 10];
    }
    

提交回复
热议问题