How can I convert all numbers that are more than 3 digits down to a 4 digit or less number?
This is exactly what I mean:
10345 = 10.3k
10012 = 10k
123546 = 123.5k
4384324 = 4.3m
Rounding is not entirely important, but an added plus.
I have looked into NSNumberFormatter but have not found the proper solution, and I have yet to find a proper solution here on SO. Any help is greatly appreciated, thanks!
Swift-4
Doble extension
- This works fine in all cases.I know there are already lots of answers and different ways, but this is how I solved it with a more functional approach:
I used gbitaudeau's answer to make this Objective-C category of NSNumberFormatter, which I use in our project (Vero.co). The NSNumberFormatter instance here created only once for the entire project.
You now can call it like that
sample usage
[Update]
Swift version below:
sample usage
Hope it helps
If you are interested in formatting bytes count, this article by Mattt Thompson shows how to use iOS/OSX builtin NSByteCountFormatter
There are also builtin formatters for energy, mass, length and a bunch of others.
The crux of it is that for most common units you do not need to write any custom code as Apple has already provided the tedious work for you. Check their online reference for NS[SomeUnit]Formatter, e.g.
MKDistanceFormatter
,NSDateIntervalFormatter
orNSDateFormatter
, etc ...You can use this simple function, the idea is easy to understand
Test