Given an int, return a string like "1st" or "13th" - Java java.lang

Java examples for java.lang:int Format

Description

Given an int, return a string like "1st" or "13th"

Demo Code


//package com.java2s;

public class Main {
    /**/* w ww . jav a2  s  . c  o m*/
     * Given an int, return a string like "1st" or "13th"
     *
     * @param i Int to ordinalize
     * @return Ordinalized string
     */
    public static String ordinal(int i) {
        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];
        }
    }
}

Related Tutorials