Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I want to take an integer and get its ordinal, i.e.:

1 -> "First" 2 -> "Second" 3 -> "Third" ... 
like image 248
lakemalcom Avatar asked Jul 24 '11 23:07

lakemalcom


People also ask

How do you convert to ordinal?

Ordinal numbers are related to their cardinal number counterparts. In English, it is usual to add two letters to a cardinal number to represent an ordinal number. For example, the cardinal numbers 1, 2 and 3 have the ordinal versions 1st, 2nd and 3rd.

Can we convert number to String in Java?

We can convert int to String in java using String. valueOf() and Integer. toString() methods. Alternatively, we can use String.


1 Answers

If you're OK with 1st, 2nd, 3rd etc, here's some simple code that will correctly handle any integer:

public static String ordinal(int i) {     String[] suffixes = 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 + suffixes[i % 10];      } } 

Here's some tests for edge cases:

public static void main(String[] args) {     int[] tests = {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, 1000};     for (int test : tests) {         System.out.println(ordinal(test));     } } 

Output:

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 1000th 
like image 84
Bohemian Avatar answered Sep 19 '22 18:09

Bohemian