Ordinal Suffixes For Numbers
Format ranks as 1st, 2nd, 3rd with ordinal suffixes, handling the 11th/12th/13th exceptions that break the last-digit rule.
Code
public class OrdinalSuffix {
// ordinal suffixes: 1st, 2nd, 3rd, but 11th/12th/13th break the last-digit rule
static String ordinalSuffix(long number) {
if (number % 100 >= 11 && number % 100 <= 13) {
return "th";
}
return switch ((int) (number % 10)) {
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
}
public static void main(String[] args) {
long[] samples = {1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 111, 1002};
for (long n : samples) {
System.out.println(n + ordinalSuffix(n));
}
}
}How it works
The working surface is the class OrdinalSuffix and the functions ordinalSuffix and main — everything else is wiring.
The loop for (long n : samples) is the only repeated construct.
Caveats
- No external surface — every behavior comes from the standard library.
Putting it to use
The signature you will reach for first is static String ordinalSuffix(long number)
Treat main as the orchestrator calling ordinalSuffix in a fixed order.
Core lines under the microscope
return switch ((int) (number % 10)) {
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
return "th";
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- How do you run Ordinal Suffixes For Numbers?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.