Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a number adding corresponding suffix to the end of it? - Java

Tags:

java

android

I need in my text view to add a number, but also I need to add the corresponding suffix to that number like 1 is 1st, 2 is 2nd and so on. Is there any way to do this instead of writing a bunch of switch statements? The number is dynamic, so it doesn't have a range. Thank you.

Detailed description:

public String getNumberWithSuffix(int number) {
    /** Add an suffix to the end of the number, convert to string and return. 
        E.g. the number is 1, the suffix needs to be 'st', 
        so we concat them and return 1st. 
        If the number is 2, the suffix needs to be 'nd', 
        we concat them and return 2nd. 
        The range is not specified so it can be any integer number. 
    **/
}
like image 563
Hayk Mkrtchyan Avatar asked Nov 24 '25 23:11

Hayk Mkrtchyan


1 Answers

Found an answer from similar question:-

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

    }
}

Link - https://stackoverflow.com/a/6810409/8762338

like image 67
Astha Garg Avatar answered Nov 26 '25 12:11

Astha Garg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!