Skip to main content

How to convert a number to its ordinal representation in Kotlin

How to convert a number to its ordinal representation in Kotlin.

Here's a step-by-step tutorial on how to convert a number to its ordinal representation in Kotlin.

Step 1: Create a function to convert the number

First, let's create a function called toOrdinal that will take a number as an input and return its ordinal representation.

fun toOrdinal(number: Int): String {
// code goes here
}

Step 2: Handle special cases

In this step, we'll handle the special cases where the ordinal representation does not follow the regular pattern. For example, numbers ending with 11, 12, and 13 are exceptions and should be represented as "th" instead of "st", "nd", or "rd".

fun toOrdinal(number: Int): String {
if (number % 100 in 11..13) {
return "${number}th"
}
// code for regular cases goes here
}

Step 3: Handle regular cases

In this step, we'll handle the regular cases where the ordinal representation follows a predictable pattern. For numbers ending with 1, 2, or 3, we'll use "st", "nd", and "rd" respectively. For all other numbers, we'll use "th".

fun toOrdinal(number: Int): String {
if (number % 100 in 11..13) {
return "${number}th"
}

return when (number % 10) {
1 -> "${number}st"
2 -> "${number}nd"
3 -> "${number}rd"
else -> "${number}th"
}
}

Step 4: Test the function

Now that we have implemented the toOrdinal function, let's test it with some sample inputs to ensure it works as expected.

fun main() {
val numbers = listOf(1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 102, 103)

for (number in numbers) {
val ordinal = toOrdinal(number)
println("The ordinal representation of $number is $ordinal")
}
}

When you run the above code snippet, you should see the following output:

The ordinal representation of 1 is 1st
The ordinal representation of 2 is 2nd
The ordinal representation of 3 is 3rd
The ordinal representation of 4 is 4th
The ordinal representation of 11 is 11th
The ordinal representation of 12 is 12th
The ordinal representation of 13 is 13th
The ordinal representation of 21 is 21st
The ordinal representation of 22 is 22nd
The ordinal representation of 23 is 23rd
The ordinal representation of 101 is 101st
The ordinal representation of 102 is 102nd
The ordinal representation of 103 is 103rd

And that's it! You have now successfully converted a number to its ordinal representation in Kotlin.