objective-c – 用于距离的Objective C字符串格式化程序

前端之家收集整理的这篇文章主要介绍了objective-c – 用于距离的Objective C字符串格式化程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个距离作为一个浮动,我正在寻找一种方式来格式很好地为人类读者.理想情况下,我希望它从m变化到km,随着它变大,并且数字很好.转换为里程将是一个奖金.我相信很多人都需要其中的一个,我希望有一些代码在某处浮动.

以下是我想要的格式:

> 0-100m:47m(整数)
> 100-1000m:325m或320m(圆到最近的5或10米)
> 1000-10000m:1.2km(圆形到最接近一个小数位)
> 10000m:21km

如果没有可用的代码,我该怎么写我自己的格式化程序?

谢谢

解决方法

这些解决方案都没有真正满足我正在寻找的东西,所以我建立在它们之上:
#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 %@",[self stringWithDistance:distance]);    

    distance = 234234.45;
    NSLog(@"%f meters is %@",[self stringWithDistance:distance]);    
}
原文链接:/c/113118.html

猜你在找的C&C++相关文章