Convert ordinal number to string [duplicate]
Asked Answered
B

1

0

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.

Buffington answered 15/12, 2017 at 13:0 Comment(11)
I am able to get ordinal number like above already using switch (i%100) Ordinal String :: 0th Ordinal String :: 1st Ordinal String :: 2ndBuffington
Are you looking for a number ordinals like 1st,2nd,3rd like?Authoritative
no. That already I am getting. I want string like first, second, third..Buffington
Are you looking like this 1 -> "First" 2 -> "Second" 3 -> "Third"Authoritative
yes. If it is possible using numbers like 1,2,3 to first, second, third.. will also be OKBuffington
Possible duplicate of https://mcmap.net/q/274241/-is-there-a-way-in-java-to-convert-an-integer-to-its-ordinal-nameAuthoritative
I have already tried from this link:: #6810836 but It is giving me errorsBuffington
@R2R I have used code from same link. but not getting result what I wantBuffington
@M.Prokhorov I have used code from same link. but not getting result what I wantBuffington
There are answers to that question that do provide alternatives to spell it out.Sworn
@Frank, because you need to use ideas from answers, not code from answers.Zoara
P
3

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.

Providing answered 15/12, 2017 at 17:33 Comment(3)
This worked for me.. Thank you.Buffington
That is an extremely poor solution when it comes to Android, as it lacks internationalization.Zoara
@M.Prokhorov quite true. The OP would probably have been much better off using a full featured library. But I had the code anyway, so I thought I'd just share it. Plus, I missed the android tag when I first answered.Providing

© 2022 - 2024 — McMap. All rights reserved.