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

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

    Bohemians answer is very good but I recommend improving the error handling. With the original version of ordinal if you supply a negative integer an ArrayIndexOutOfBoundsException will be thrown. I think my version below is clearer. I hope the junit is also useful so it is not necessary to visually check the output.

    public class FormattingUtils {
    
        /**
         * Return the ordinal of a cardinal number (positive integer) (as per common usage rather than set theory).
         * {@link http://stackoverflow.com/questions/6810336/is-there-a-library-or-utility-in-java-to-convert-an-integer-to-its-ordinal}
         * 
         * @param i
         * @return
         * @throws {@code IllegalArgumentException}
         */
        public static String ordinal(int i) {
            if (i < 0) {
                throw new IllegalArgumentException("Only +ve integers (cardinals) have an ordinal but " + i + " was supplied");
            }
    
            String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
            switch (i % 100) {
            case 11:
            case 12:
            case 13:
                return i + "th";
            default:
                return i + sufixes[i % 10];
            }
        }
    }
    
    
    import org.junit.Test;
    import static org.assertj.core.api.Assertions.assertThat;
    
    public class WhenWeCallFormattingUtils_Ordinal {
    
        @Test
        public void theEdgeCasesAreCovered() {
            int[] edgeCases = { 0, 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 100, 101, 102, 103, 104, 111, 112,
                    113, 114 };
            String[] expectedResults = { "0th", "1st", "2nd", "3rd", "4th", "5th", "10th", "11th", "12th", "13th", "14th",
                    "20th", "21st", "22nd", "23rd", "24th", "100th", "101st", "102nd", "103rd", "104th", "111th", "112th",
                    "113th", "114th" };
    
            for (int i = 0; i < edgeCases.length; i++) {
                assertThat(FormattingUtils.ordinal(edgeCases[i])).isEqualTo(expectedResults[i]);
            }
        }
    
        @Test(expected = IllegalArgumentException.class)
        public void supplyingANegativeNumberCausesAnIllegalArgumentException() {
            FormattingUtils.ordinal(-1);
        }
    
    }
    

提交回复
热议问题