7

I would like to convert numbers to the shorter form using NSNumberFormatter.

For example: From 23000 to get 23K.

How I can do it using NSNumberFormatter?

I know it is possible to do calculation on my own, but in my case it is not right way to go.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Ramis
  • 13,985
  • 7
  • 81
  • 100
  • Do you want that 23340 become 23k too, or not? – Lolloz89 Jun 19 '12 at 08:23
  • @Lolloz89 was about to ask the same. And 23850? Should it be 23k or 24k? – Novarg Jun 19 '12 at 08:24
  • The point is that the "k" suffix is not recognized as a standard and international pattern. Anyway I think that if you want to use this pattern is because you don't want be so precise in representing a value, so I guess 23890 --> 23k. I'll write an answer to do this without using NSNumberFormatter. – Lolloz89 Jun 19 '12 at 08:30
  • 1
    a nice solution: http://stackoverflow.com/a/4716523/106435 – vikingosegundo Jun 19 '12 at 08:31
  • possible duplicate of [ObjC/Cocoa class for converting size to human-readable string?](http://stackoverflow.com/questions/572614/objc-cocoa-class-for-converting-size-to-human-readable-string) – JeremyP Jun 19 '12 at 08:52
  • The solution linked by @vikingosegundo is better than the solution that was accepted because it uses an NSFormatter subclass. – JeremyP Jun 19 '12 at 08:53

1 Answers1

4

The 'K' suffix is not recognized as standard, so you can't do this using NSNumberFormatter. anyway this is a simple way to do that.

-(NSString *)kFormatForNumber:(int)number{
    int result;
    if(number >= 1000){ 
        result = number/1000;

        NSString *kValue = [NSString stringWithFormat:@"%dk",result];
        return kValue;
    }
    return [NSString stringWithFormat:@"%d",number];
}
lxt
  • 31,146
  • 5
  • 78
  • 83
Lolloz89
  • 2,809
  • 2
  • 26
  • 41