我有一段距离,就像浮游物一样,我正在寻找一种可以很好地为人类读者格式化的方式。理想情况下,我希望它随着m的增大而从m更改为km,并很好地舍入该数字。转换为英里将是一个奖励。我确信很多人都需要其中之一,并且我希望某个地方有一些代码。
这是我想要的格式:
如果没有可用的代码,如何编写自己的格式化程序?
谢谢
最佳答案
这些解决方案都无法真正满足我的需求,因此我在这些解决方案的基础上:
#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]);
}
关于objective-c - 用于距离的 objective-c 字符串格式化程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2324125/