Search code examples
objective-cnumberformatter

NumberFormatter - ObjectiveC


How do I create a number formatter for formatting large numbers with commas?

For example, 2389378.289 should become 2,389,378.289

Note that there is not always three decimal places, nor is there always a decimal at all. Please use NSNumberFormatter.

Thanks!


Solution

  • NSNumberFormatter *fmt = [[[NSNumberFormatter alloc] init] autorelease];
    [fmt setAlwaysShowsDecimalSeparator:NO];
    [fmt setFormat:@"#,##0.###"];
    NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:35.424252]]);
    NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:21.3]]);
    NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:10392425]]);
    

    The format Chuck gave you supports up to 3 decimal places. If you have a number with less than 3 they just don't show up. Chuck is also correct that you want to take a look at the Unicode number format guide, it is invaluable for number formatting issues.