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]);
}