Search code examples
ioscocoa-touchformattingnsnumberformatter

Adding Commas to Float or String?


I have been trying to find a way to find a way to append commas to a string or float. I have a float which could be anything from 10.50 to 50000000000.99 and would love to be able to format this to add commas to every 3 digits (not including the floats). I know that there is a NSNumberFormatter that can use NSNumberFormatterDecimalStyle or NSNumberFormatterCurrencyStyle but neither of those work with strings/floats. I have tried to split the float into two strings and then try to do a % of length == 3 calculation but it began to get really really messy. I did something similar in Java but it seems to be a lot harder in iOS.

If anyone have any suggestions or ideas? Any information or guidance is appreciated! Thanks in advance.

Edit: I know there are posts out there but none of them seem to solve the problem with doubles/floats/strings that end in zeros. For example, if I have a double as 16.00, the formatter will format that into 16. Same thing goes for a 1234.80. The formatter will format it into 1,234.8 instead of 1,234.80 and that is what I am looking for.


Solution

  • View this post on NSNumberFormatting here

    The gist of it is to covert the float or double to a NSNumber and then use the NSNumberFormatter on the NSNumber to get a NSString with the desired format. Something like:

    double doubleNum = 1000.002;
    
    // Change double to nsnumber:
    NSNumber *num = [NSNumber numberWithDouble:doubleNum];
    
    // Set up the formatter:
    NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
    [numFormatter setUsesGroupingSeporator:YES];
    [numFormatter setGroupingSeparator:@","];
    [numFormatter setGroupingSize:3];
    
    // Get the formatted string:
    NSString *stringNum = [numFormatter stringFromNumber:num];
    
    NSLog(@"%@",stringNum);
    // prints out '1,000.002'
    

    Give it a try, there are lots of different formatting settings you can apply.