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];

 

Advertisements

How to restrict user for only IntegerValue in UITextfield for iPad/iPhone?


Hi,

There are some situations where we required that User should input only numeric value like 0to9.In that kind of situation we have to use this tricks with UITextField’s delegate method.

– (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSNumber* candidateNumber;

NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];

range = NSMakeRange(0, [candidateString length]);

[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];

if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length]))

{

return NO;

}

else

{

return YES;

}

}