1

Similar to comma separated thousand NSString stringWithFormat but with a specific use case.

How do I insert a comma (,) after every third digit?

Some cases:

  • 9999999 → 9,999,999
  • 1234 → 1,234
  • 3432423455435435 → 3,432,423,455,435,435

The results are expected regardless of locale or any other circumstance.

Community
  • 1
  • 1
Jonny
  • 15,955
  • 18
  • 111
  • 232

2 Answers2

4

You're looking for an NSNumberFormatter. The easiest way to use it is like this:

NSString *formatted = [NSNumberFormatter localizedStringFromNumber:@(1234) numberStyle:NSNumberFormatterDecimalStyle];
NSLog(@"%@", formatted); // probably logs "1,234", depending on your locale.
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • This time I don't need locales, I want to make sure I always get the same result. – Jonny Apr 18 '13 at 02:05
  • 2
    @Jonny If you always want the same result, regardless of the user's locale, then you must set an explicit locale on the `NSNumberFormatter` instance. This must mean the resulting string is not meant to be seen by the user. – rmaddy Apr 18 '13 at 02:07
  • A specific locale could be ok but which one fulfills my question? – Jonny Apr 22 '13 at 00:02
  • @Jonny You use an `NSNumberFormatter` because you want to show a number to a human. You should respect that human's preferences, so you should use `[NSLocale currentLocale]`. That's what `+localizedStringFromNumber:numberStyle:` will use. For more info, watch WWDC 2012 session 244: Internationalization Tips & Tricks. – Dave DeLong Apr 22 '13 at 00:28
  • You might have a point (and I agree with you), still I'm told to do what is in the question and yes the text will be read by humans. I'm not gonna ask my boss to go watch WWDC 2012. I ended up doing some string juggling. – Jonny Apr 22 '13 at 01:50
0

What I needed was not something that would care for the locale of a user, and with that it was just easier to do some string juggling. If someone cares I could dig up that code...

If you however DO care for locales, go with the other answer of Dave DeLong. Technically however it does not answer the question.

Jonny
  • 15,955
  • 18
  • 111
  • 232