I have a distance as a float and I'm looking for a way to format it nicely for human readers. Ideally, I'd like it to change from m to km as it gets bigger, and to round the number nicely. Converting to miles would be a bonus. I'm sure many people have had a need for one of these and I'm hoping that there's some code floating around somewhere.
Here's how I'd like the formats:
If there's no code available, how can I write my own formatter?
Thanks
None of these solutions really met what I was looking for, so I built on them:
#define METERS_TO_FEET 3.2808399
#define METERS_TO_MILES 0.000621371192
#define METERS_CUTOFF 1000
#define FEET_CUTOFF 3281
#define FEET_IN_MILES 5280
- (NSString *)stringWithDistance:(double)distance {
BOOL isMetric = [[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue];
NSString *format;
if (isMetric) {
if (distance < METERS_CUTOFF) {
format = @"%@ metres";
} else {
format = @"%@ km";
distance = distance / 1000;
}
} else { // assume Imperial / U.S.
distance = distance * METERS_TO_FEET;
if (distance < FEET_CUTOFF) {
format = @"%@ feet";
} else {
format = @"%@ miles";
distance = distance / FEET_IN_MILES;
}
}
return [NSString stringWithFormat:format, [self stringWithDouble:distance]];
}
// Return a string of the number to one decimal place and with commas & periods based on the locale.
- (NSString *)stringWithDouble:(double)value {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:1];
return [numberFormatter stringFromNumber:[NSNumber numberWithDouble:value]];
}
- (void)viewDidLoad {
[super viewDidLoad];
double distance = 5434.45;
NSLog(@"%f meters is %@", distance, [self stringWithDistance:distance]);
distance = 543.45;
NSLog(@"%f meters is %@", distance, [self stringWithDistance:distance]);
distance = 234234.45;
NSLog(@"%f meters is %@", distance, [self stringWithDistance:distance]);
}
iOS 7 and OS X 10.9 introduced MKDistanceFormatter for formatting distances:
Code Example:
double myDistance = 21837.0f;
MKDistanceFormatter *df = [[MKDistanceFormatter alloc]init];
df.unitStyle = MKDistanceFormatterUnitStyleAbbreviated;
NSLog(@"myDistance is %@", [df stringFromDistance: myDistance]);
Update:
It seems that MKDistanceFormatter is rounding the input value somehow. E.g. when I set myDistance to 111.0 I get "100 m".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With