10

我有一个浮动距离,我正在寻找一种为人类读者很好地格式化它的方法。理想情况下,我希望它在变大时从 m 变为 km,并很好地舍入数字。转换为里程将是一个奖励。我相信很多人都需要其中之一,我希望有一些代码在某处浮动。

这是我想要的格式:

  • 0-100m:47m(整数)
  • 100-1000m:325m或320m(四舍五入到最近的5或10米)
  • 1000-10000m:1.2km(四舍五入,保留一位小数)
  • 10000米+:21公里

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

谢谢

4

7 回答 7

25

这些解决方案都没有真正满足我的要求,所以我建立在它们之上:

#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]);    
}
于 2011-04-16T06:43:34.750 回答
23

iOS 7 和 OS X 10.9 引入了MKDistanceFormatter来格式化距离:

代码示例:

double myDistance = 21837.0f;

MKDistanceFormatter *df = [[MKDistanceFormatter alloc]init];
df.unitStyle = MKDistanceFormatterUnitStyleAbbreviated;

NSLog(@"myDistance is %@", [df stringFromDistance: myDistance]);

更新:

似乎 MKDistanceFormatter 以某种方式舍入了输入值。例如,当我将 myDistance 设置为 111.0 时,我得到“100 m”。

于 2014-02-01T16:55:01.133 回答
17

是的,您需要编写自己的格式化程序,例如

#include <math.h>
NSString* convertDistanceToString(float distance) {
    if (distance < 100)
       return [NSString stringWithFormat:@"%g m", roundf(distance)];
    else if (distance < 1000)
       return [NSString stringWithFormat:@"%g m", roundf(distance/5)*5];
    else if (distance < 10000)
       return [NSString stringWithFormat:@"%g km", roundf(distance/100)/10];
    else
       return [NSString stringWithFormat:@"%g km", roundf(distance/1000)];
}
...
NSLog(@"The distance is %@", convertDistanceToString(1024));
于 2010-02-24T06:37:51.050 回答
4

NSLengthFormatter这是随着 iOS 8 和 OS X 10.10 引入的,这是人们应该注意的一个选项。

    NSLengthFormatter *lengthFormatter = [[NSLengthFormatter alloc] init];
    lengthFormatter.unitStyle = NSFormattingUnitStyleShort;

    NSLog(@"distance = %@", [lengthFormatter stringFromMeters:meters]);

但是,NSLengthFormatter在那些使用公制的语言环境中,除了距离之外,has 不使用英制单位。

于 2015-09-02T10:35:49.840 回答
2

这是我的做法。这使用用户的语言环境来正确格式化字符串,您可能也应该这样做。

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

}
于 2010-02-24T06:53:14.487 回答
0

今天发现这个问同样的问题....继续:

NSString *右值;
    如果(值 > 1000){
        rvalue = [NSString stringWithFormat:@"%.02f km",value];
    }别的 {
        rvalue = [NSString stringWithFormat:@"%.02f m",value];
    }

如果需要,可以将其包装在一个方法中

于 2010-04-18T01:17:11.197 回答
-1

对于那些寻找 swift 2.0 版本的人。从@MattDiPasquale 移植

 extension Double {
  func toDistanceString() -> String {
    let METERS_TO_FEET = 3.2808399
    let METERS_CUTOFF = 1000.0
    let FEET_CUTOFF = 3281.0
    let FEET_IN_MILES =  5280.0

    let format:String
    if (NSLocale.isMetric()) {
      if (self < METERS_CUTOFF) {
        format = "\(self.stringWithDecimals(0)) metres"
      } else {
        format = "\((self / 1000).stringWithDecimals(1)) km";
      }
    } else { // assume Imperial / U.S.
      let feet = self * METERS_TO_FEET;
      if (feet < FEET_CUTOFF) {
        format = "\(feet.stringWithDecimals(0)) feet";
      } else {
        format = "\((self / FEET_IN_MILES).stringWithDecimals(1)) miles";
      }
    }
    return format
  }

  func stringWithDecimals(decimals:Int) -> String {
    return String(format: "%.\(decimals)f", self)
  }
}

extension NSLocale {
  class func isMetric() -> Bool {
    let locale = NSLocale.currentLocale()
    return locale.objectForKey(NSLocaleUsesMetricSystem) as! Bool
  }
}
于 2015-10-18T01:23:17.160 回答