Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a (large) number "12345" to "12,345"

Say I have a large number (integer or float) like 12345 and I want it to look like 12,345.

How would I accomplish that?

I'm trying to do this for an iPhone app, so something in Objective-C or C would be nice.

like image 249
Kriem Avatar asked May 06 '09 16:05

Kriem


3 Answers

Here is the answer.

  NSNumber* number = [NSNumber numberWithDouble:10000000];
  NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
  [numberFormatter setNumberStyle:kCFNumberFormatterDecimalStyle];
  [numberFormatter setGroupingSeparator:@","];
  NSString* commaString = [numberFormatter stringForObjectValue:number];
  [numberFormatter release];
  NSLog(@"%@ -> %@", number, commaString);
like image 67
wookay Avatar answered Oct 26 '22 07:10

wookay


Try using an NSNumberFormatter.

This should allow you to handle this correctly on an iPhone. Make sure you use the 10.4+ style, though. From that page:

"iPhone OS: The v10.0 compatibility mode is not available on iPhone OS—only the 10.4 mode is available."

like image 20
Reed Copsey Avatar answered Oct 26 '22 05:10

Reed Copsey


At least on Mac OS X, you can just use the "'" string formatter with printf(3).

$ man 3 printf

     `''          Decimal conversions (d, u, or i) or the integral portion
                  of a floating point conversion (f or F) should be
                  grouped and separated by thousands using the non-mone-
                  tary separator returned by localeconv(3).

as in printf("%'6d",1000000);

like image 29
user102629 Avatar answered Oct 26 '22 06:10

user102629