Cocoa: Convert number to comma-separated NSString

At some point in your Mac, iPhone, or iPad development you may find the need to express a long number (1000000000) as a comma-separated string (1,000,000,000) to make life easier on your users. The NSNumberFormatter class is a rich tool for converting numbers to strings supporting different types of currencies and localizations. It’s also the perfect class to leverage for our comma-ing task.

First of all, the NSNumberFormatter class works on NSNumber objects, so we need to convert our number to a NSNumber if it’s not there already.
NSNumber *number = [NSNumber numberWithInt:1000000000];

NSNumber also supports floating point values (numberWithFloat) and the regular gang of other number formats.

With our NSNumber in hand, we can get on with the good stuff. NSNumberFormatter supports grouping of numeric digits into arbitrary length groups (we want groups of three) and separating the groups with arbitrary strings (we want to use a comma (@”,”) but we could use any string). Here’s the code that makes our string:

NSNumberFormatter *frmtr = [[NSNumberFormatter alloc] init];
[frmtr setGroupingSize:3];
[frmtr setGroupingSeparator:@","];
[frmtr setUsesGroupingSeparator:YES];
NSString *commaString = [frmtr stringFromNumber:number];

Read more about NSNumberFormatter’s crazy tricks here. It can also do cool things like spelling out a number like 42 into forty-two and handling significant digits.

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

6 Responses to “Cocoa: Convert number to comma-separated NSString”

  1. April 30, 2010 at 9:32 am, Anonymous said:

    HOW I RUN XP BASED PROGRAM IN WINDOWS7

    Reply

  2. May 20, 2010 at 1:08 am, Susan said:

    What about all the countries that don’t use “3 digits” and don’t use “commas”????

    How would you write code that worked e-v-e-r-y-w-h-e-r-e, not just in small parts of the world?

    Reply

    • May 25, 2010 at 3:20 am, Aaron said:

      Well, I have thought long and hard about this particular issue — the one with commas versus periods. I have come to the conclusion that the United States, and any other country that uses the comma style, is correct.

      Think: In a sentence, a comma symbolizes a pause; there will be more to com in the thought shortly. A period symbolizes the end of a thought and the start of another. Here’s an example number: 123,456.789 … That’s One-hundred-twenty-three-thousand four-hundred-fifty-six and seven-hundred-eighty-nine thousandths.

      The integer part of the number is 123456. The comma between the sets of three is a pause; more of the “thought” will follow after the 123. To put it another way, more of the integer part of the number will be read shortly.

      Imagine if a period was used: The end of the “thought” would come at the period in regular writing. The thing is, when a period is used, you split the integer part of the number in half. Why should the “thought” end halfway through one part of the number? The “thought” should continue until the integer part of the number is finished.

      Anyway, that’s why I think the period should symbolize the start of the decimal part of a number rather than a comma. We should keep math and writing consistent, don’t you think?

      I hate defending the United States of America in this way, but I think we’re right for once. … Hey, I live here and I think most of the people are culturally illiterate buffoons, but I’ll cut us some slack this time. We’re right, anyone who thinks differently is wrong.

      Reply

      • October 24, 2013 at 4:26 pm, Frank said:

        Wow, Aaron. I almost don’t know where to begin.

        You’re using American English punctuation to justify universal number formatting. What about languages that don’t use “.” for sentences, or “,” for pauses? You assert that “We should keep math and writing consistent”, but don’t explain why you think it’s better to keep all numbers consistent with English writing, rather than consistent with the local writing system.

        You say that since “,” means a pause when reading a sentence, it makes sense that it means a pause when reading a number, and “.” means a break so it should mean a break between “ones” and “tenths”. But if that’s so, then even in English it would be better to use the SI convention of spaces between groups of digits, and “,” for the slightly bigger pause between “ones” and “tenths”, and reserve “.” for even bigger groupings, like sentence structure.

        Finally, all of this ignores that there’s a really simple answer to the question as asked: [NSNumberFormatter localizedStringFromNumber: X numberStyle: NSNumberFormatterDecimalStyle]. It uses the correct separators based on the user’s locale automatically. There’s no need to try to justify “America’s way is Right and everybody else is Wrong”, because it’s trivial to give each user exactly what they want.

        Reply

  3. August 05, 2010 at 10:52 am, test said:

    How do I force the number formatter to display 1.25m instead of 1,250,000, etc? Thanks

    Reply

  4. June 27, 2012 at 9:22 am, clement said:

    thank you very much. very useful post.

    Reply

Leave a Reply