Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Conversion to Ordinal Format

Tags:

android

Before I go reinventing the wheel, does Android have any facility for converting an integer to an ordinal string with multi-language support? That is, it would convert the integer 3 to "3rd" in English and "3eme" in French.

I can see how to do this myself using a bit of logic along with Android's automatic string substitution, but thought that this surely must have been encountered by others, and not just for use with dates.

like image 674
gordonwd Avatar asked Mar 17 '12 13:03

gordonwd


3 Answers

Just for future reference, I came across this issue and discovered that now you can use the ICU MessageFormat to do something like this:

import android.icu.text.MessageFormat

fun toOrdinal(day: String): String {
    val formatter = MessageFormat("{0,ordinal}", Locale.getDefault())
    return formatter.format(arrayOf(day.toInt()))
}

You will get these results:

1 -> 1st
2 -> 2nd
3 -> 3rd
4 -> 4th
5 -> (...)
like image 111
Rui Avatar answered Oct 24 '22 03:10

Rui


If the range for which you need ordinals is limited, then you are probably best to use a <string-array> to define them:

<string-array name="ordinals">
  <item>zeroth</item>
  <item>1st</item>
  <item>2nd</item>
  <item>3rd</item>
  <item>4th</item>
  <item>5th</item>
  <item>6th</item>
</string-array>

and then access it via:

String ordinal = getResources().getStringArray(R.array.ordinals)[count];

Of course this doesn't get you automatic translation into other languages - you have to do that yourself (and if your count goes outside the range in this simplistic code you will get an exception).

like image 21
zmarties Avatar answered Oct 24 '22 03:10

zmarties


Java nor Android have support for creating ordinal strings. Android does have support for creating plural string resources, but not ordinals.

like image 7
CommonsWare Avatar answered Oct 24 '22 03:10

CommonsWare