Y2theZ
Y2theZ

Reputation: 10412

Custom Formatting of an NSNumber

in an ios application, I am trying to allow the user to enter a number and a format and I want to get a string with that number formatted as the user specified:

For that I have tried this:

- (NSString *)formatNumber:(NSNumber *)number withFormat:(NSString *)format
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
   [formatter setPositiveFormat:format];
    NSString *formatedString = [formatter stringFromNumber:number];
    return formatedString;
}

but if I try to call something like this:

NSNumber *number = [NSNumber numberWithDouble:1234567890];
NSString *string = [self formatNumber:number withFormat:@"###-###-####"];

I was expecting to get a result: 123-456-7890

But it is not working.

is the @"###-###-####" format wrong syntax ? or am I using the NSNumberFormatter wrong?

Thanks for any help

PS: I do not want to hard code an algorithm to loop through the characters and insert the dashes (-) because that format is just an example as the user is able to freely change it.

Thanks

EDIT

SORRY while writting my code here I missed a line. now added it

Upvotes: 0

Views: 508

Answers (1)

James
James

Reputation: 667

This may be useful:

https://discussions.apple.com/thread/2399192

Key quote:

Parentheses and dashes are not allowed in a number format.

Upvotes: 1

Related Questions