NSLengthFormatter gets stringFromMeters: in kilometers / kilometers only

I am using NSLengthFormatter class to format the distance between the user and some destination.

CLLocation *userLocation; //<- Coordinates fetched from CLLocationManager
CLLocation *targetLocation; //<- Some location retrieved from server data

CLLocationDistance distance = [userLocation distanceFromLocation:targetLocation];

NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
NSString *formattedLength = [lengthFormatter stringFromMeters:distance];

      

Now, if the length is less than 1000 meters, the formatted distance is always displayed in yards or meters (depending on the locale).

Eg. if distance = 450.0, the formatted string will be 492.7 or 450 m.

How can I configure NSLengthFormatter to return distance strings in kilometers / kilometers only?

+3


source to share


2 answers


It is impossible to refuse such behavior. To be honest, your requirement is not very common in terms of UX.

Note that meter

is the base unit, not kilometer

(thousand meters). Usually display is 10 meters

preferable to display 0.01 kilometers

. It is more user friendly.

In fact, it would be very difficult to design an API that enforces a specific unit, given that the base unit depends on the current locale.



You can use a specific block using:

- (NSString *)unitStringFromValue:(double)value unit:(NSLengthFormatterUnit)unit;

      

but you will have to handle the locale and scaling and unit conversion yourself (see Objective c string formatter for distances )

+3


source


Here's what I ended up using:



-(NSString *)formattedDistanceForMeters:(CLLocationDistance)distance
 {
    NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
    [lengthFormatter.numberFormatter setMaximumFractionDigits:1];

    if ([[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue])
    {
        return [lengthFormatter stringFromValue:distance / 1000 unit:NSLengthFormatterUnitKilometer];
    }
    else
    {
        return [lengthFormatter stringFromValue:distance / 1609.34 unit:NSLengthFormatterUnitMile];
    }
}

      

+7


source







All Articles