Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using locale settings to detect wheter to use imperial units

I'm working on an app that wants to display lengths either in centimeters (cm) or in inches("). Is there a way to select the right unit from the locale? In any event I'm also going to put in an option so that the user can to override the locale setting.

USA, Liberia, and Burma should use imperial units and the rest of the world normal units. One way is to put in this logic in my own classes, but I would prefer using any built in logic if available. Any pointers?

like image 749
vidstige Avatar asked Feb 04 '11 13:02

vidstige


1 Answers

In the end I went for the following solution.

public class UnitLocale {     public static UnitLocale Imperial = new UnitLocale();     public static UnitLocale Metric = new UnitLocale();      public static UnitLocale getDefault() {             return getFrom(Locale.getDefault());     }     public static UnitLocale getFrom(Locale locale) {         String countryCode = locale.getCountry();         if ("US".equals(countryCode)) return Imperial; // USA         if ("LR".equals(countryCode)) return Imperial; // Liberia         if ("MM".equals(countryCode)) return Imperial; // Myanmar         return Metric;     } } 

Use it like this for example.

if (UnitLocale.getDefault() == UnitLocale.Imperial) convertToimperial(); 

If convert methods are also need they can preferably be added to subclasses of UnitLocale. I only needed to detect wheter to use imperial units and send it to the server.

Using ints over java objects have extremely slim performance gains and makes the code harder to read. Comparing two references in java is comparable in speed to comparing two ints. Also using objects allow us to add methods to the UnitLocale class or subclasses such as, convertToMetric, etc.

You could also use an enum instead if you prefer that.

like image 166
vidstige Avatar answered Oct 01 '22 18:10

vidstige