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&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...