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

后端 未结 12 1311
生来不讨喜
生来不讨喜 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:41

    Another solution

    public static String ordinal(int i) {
        int mod100 = i % 100;
        int mod10 = i % 10;
        if(mod10 == 1 && mod100 != 11) {
            return i + "st";
        } else if(mod10 == 2 && mod100 != 12) {
            return i + "nd";
        } else if(mod10 == 3 && mod100 != 13) {
            return i + "rd";
        } else {
            return i + "th";
        }
    }
    

    Pro: does not require an array to be initialized (less garbage)
    Con: not a one-liner...

提交回复
热议问题