5

How could I know in android whether to use metric or imperial? I haven't seen any option in Locale, and the only thing that comes to my mind is to use the locale.getCountry(); method and check whether the country is UK, US, ... But, is there an android's method to know it?

Thanks in advance!

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
FVod
  • 2,245
  • 5
  • 25
  • 52
  • Locale.getLocale() i think, if uk or us or australi use metric, or make a user chose between metric and standard. or watch the METRIC class – David Mar 17 '16 at 15:34
  • 2
    This is interesting, but I don't think it's described in a locale. Some apps where it's relevant (I'm thinking Tinder) offer the user to choose between the two. – MPelletier Mar 17 '16 at 15:35
  • 2
    Tinder? inches or centimetres? ;) – Mitch Wheat Mar 17 '16 at 15:36
  • 3
    @MitchWheat Good one! It's for range, so it's miles or kilometers. – MPelletier Mar 17 '16 at 15:39
  • @MitchWheat jajaja. Is there some way to get the device's default metric? Or should I use the getCountry method? – FVod Mar 17 '16 at 15:49
  • 2
    That isn't built into Android. Your best bet is to use the country as default, and allow the user to override. And of course inside your app pick one (preferably metric) as the internal type to use and just translate it when it goes out to the display/comes in from a user input. – Gabe Sechan Mar 17 '16 at 15:57
  • Here's a similar question for IOS: https://stackoverflow.com/questions/7413144/how-do-i-know-which-is-the-default-measure-system-imperial-or-metric-on-ios – StayOnTarget Aug 08 '18 at 12:37

2 Answers2

2

A more or less complete way to do this is this way:

Kotlin:

private fun Locale.toUnitSystem() =
    when (country.toUpperCase()) {
        // https://en.wikipedia.org/wiki/United_States_customary_units
        // https://en.wikipedia.org/wiki/Imperial_units
        "US" -> UnitSystem.IMPERIAL_US
        // UK, Myanmar, Liberia, 
        "GB", "MM", "LR" -> UnitSystem.IMPERIAL
        else -> UnitSystem.METRIC
    }

Note that there is a difference between UK and US imperial systems, see the wiki articles for more details.

joecks
  • 4,539
  • 37
  • 48
  • why do you categorize GB as imperial? A quick google search tells me that GB uses both – Tim Nov 06 '18 at 15:10
  • Yes this is a good comment. I guess it depends on what you need. In my case it is used for distances which seems to be pretty fitting. Maybe it would be better to provide functions for the units you want to distinguish. – joecks Nov 07 '18 at 18:18
1

I use this extension function for Kotlin:

fun Locale.isMetric(): Boolean {
    return when (country.uppercase(this)) {
        "US", "LR", "MM", "BS", "BZ", "KY", "PW", "GB", "UK" -> false
        else -> true
    }
}
Codelaby
  • 2,604
  • 1
  • 25
  • 25