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 number nicely. Converting to miles would be a bonus. I'm sure many people have had a need for one of these and I'm hoping that there's some code floating around somewhere.
Here's how I'd like the formats:
- 0-100m: 47m (as a whole number)
- 100-1000m: 325m or 320m (round to the nearest 5 or 10 meters)
- 1000-10000m: 1.2km (round to nearest with one decimal place)
- 10000m +: 21km
If there's no code available, how can I write my own formatter?
Thanks
None of these solutions really met what I was looking for, so I built on them:
Yes you need to write your own formatter, like
NSLengthFormatter
which was introduced with iOS 8 and OS X 10.10 is an option people should be aware of.However,
NSLengthFormatter
has doesn't use Imperial units in those locales where they use metric except for distances.found this today asking the same question....going with :
could wrap this in a method, if need be
Here's how I do it. This uses the locale of the user to properly format the string, which you should probably do too.
iOS 7 and OS X 10.9 introduced MKDistanceFormatter for formatting distances:
Code Example:
Update:
It seems that MKDistanceFormatter is rounding the input value somehow. E.g. when I set myDistance to 111.0 I get "100 m".