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

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

    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";
        }
    }
    

提交回复
热议问题