Objective c string formatter for distances

后端 未结 7 1826
借酒劲吻你
借酒劲吻你 2021-02-02 01:45

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

7条回答
  •  情话喂你
    2021-02-02 02:21

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

提交回复
热议问题