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 n
Here's how I do it. This uses the locale of the user to properly format the string, which you should probably do too.
// Returns a string representing the distance in the correct units.
// If distance is greater than convert max in feet or meters,
// the distance in miles or km is returned instead
NSString* getDistString(float distance, int convertMax, BOOL includeUnit) {
NSString * unitName;
if (METRIC) {
unitName = @"m";
if (convertMax != -1 && distance > convertMax) {
unitName = @"km";
distance = distance / 1000;
}
} else {
unitName = @"ft";
if (convertMax != -1 && distance > convertMax) {
unitName = @"mi";
distance = distance / 5280;
}
distance = metersToFeet(distance);
}
if (includeUnit) return [NSString stringWithFormat:@"%@ %@", formatDecimal_1(distance), unitName];
return formatDecimal_1(distance);
}
// returns a string if the number with one decimal place of precision
// sets the style (commas or periods) based on the locale
NSString * formatDecimal_1(float num) {
static NSNumberFormatter *numFormatter;
if (!numFormatter) {
numFormatter = [[[NSNumberFormatter alloc] init] retain];
[numFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numFormatter setLocale:[NSLocale currentLocale]];
[numFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numFormatter setMaximumFractionDigits:1];
[numFormatter setMinimumFractionDigits:1];
}
return [numFormatter stringFromNumber:F(num)];
}