Convert ordinal number to string

1.8k Views Asked by At

I am retrieving ordinal numbers using below code:

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];

    }
}

Output : 1st, 2nd, 3rd...

How can I get string like first, second, third from these ordinal numbers in java, Android.

1

There are 1 best solutions below

3
On BEST ANSWER

You can use this class I wrote. Just download the file (license header included) to your project, update the package declaration, and you can use it like this.

Numerals ns = new Numerals();
System.out.println(ns.toWords(12048));
System.out.println(ns.toWords(12048, true));
System.out.println(ns.toWords(102500, false));
System.out.println(ns.toWords(102500, true));

which outputs

twelve thousand and forty-eight
twelve thousand and forty-eighth
one hundred and two thousand, five hundred
one hundred and two thousand, five hundredth

The second argument to toWords, if specified, determines whether to output ordinals (true) or regular numerals (false). You can take a look at it to see how it works.