Share this page 

Get short ordinal representation of a number Tag(s): String/Number



import java.util.Locale;



public class NumberUtils {



  private NumberUtils() { }



  /*

   * Ordinal (depends on the current locale)

   *  French or english support

   */

  public static String getOrdinal(int number) {

    if (Locale.getDefault().getLanguage().equals("fr")) {

      return NumberUtils.getOrdinalFr(number);

    }

    else {

      return NumberUtils.getOrdinalEn(number);

    }

  }





  public static String getOrdinalFr(int number) {

    if(number == 1 ) {

        return number + "ier";

    }

    else {

        return number + "e";

    }

  }



  public static String getOrdinalEn(int number) {

    int mod100 = number % 100;

    int mod10 = number % 10;

    if(mod10 == 1 && mod100 != 11) {

        return number + "st";

    }

    else if(mod10 == 2 && mod100 != 12) {

        return number + "nd";

    }

    else if(mod10 == 3 && mod100 != 13) {

        return number + "rd";

    } else {

        return number + "th";

    }

  }



  public static void main(String[] args) throws Exception{

    int[] testCases = { 0, 1, 2, 3, 4, 5, 10,

                        11, 12, 13, 14, 20, 21, 22,

                        23, 24, 100, 101, 102, 103,

                        104, 1000, 1001, 1002 };

    for (int testCase : testCases) {

        System.out.println(NumberUtils.getOrdinal(testCase));

        //System.out.println(NumberUtils.getOrdinalEn(testCase));

        //System.out.println(NumberUtils.getOrdinalFr(testCase));



        /*

          output (english)

          0th

          1st

          2nd

          3rd

          4th

          5th

          10th

          11th

          12th

          13th

          14th

          20th

          21st

          22nd

          ...

         */

    }

  }

}