Frederick C. Lee
Frederick C. Lee

Reputation: 9513

NSNumberFormatter customize?

I wish to use NSNumberFormatter to merely attached a percent ('%') to the supplied number WITHOUT having it multiplied by 100.

The canned kCFNumberFormatterPercentStyle automatically x100 which I don't want.

For example, converting 5.0 to 5.0% versus 500%.

Using the following:

NSNumberFormatter *percentFormatter = [[NSNumberFormatter alloc] init];
[percentFormatter setNumberFormat:@"##0.00%;-##0.00%"];

But 'setNumberFormat' doesn't exist in NSNumberFomatter.

I need to use this NSNumberFormatter for my Core-Plot label.

How can I customize NSNumberFormat?

Ric.

Upvotes: 2

Views: 913

Answers (2)

Frederick C. Lee
Frederick C. Lee

Reputation: 9513

Source: Apple's NSDecimalNumber reference.

Apparently I hinted the answer by saying that I didn't want the output to be 100x. I'm working with a NSDecimalNumber which has the 'setMultiplier' method.

So, after I used the canned kCFNumberFormatterPercentStyle for the formatter,
I used 'setMultiplier:1' as follows:

 NSNumberFormatter *percentFormatter = [[NSNumberFormatter alloc] init];
 [percentFormatter setNumberStyle:kCFNumberFormatterPercentStyle];
 [percentFormatter setMultiplier:[NSNumber numberWithInt:1]];

Upvotes: 3

highlycaffeinated
highlycaffeinated

Reputation: 19867

Have you tried using setMultiplier to prevent it from multiplying by 100?

NSNumberFormatter *percentFormatter = [[NSNumberFormatter alloc] init];
[percentFormatter setNumberStyle: NSNumberFormatterPercentStyle];
[percentFormatter setMultiplier:1];

If adding the percent sign is all you need to accomplish, an alternative using NSNumberFormatterwould be:

[NSString stringWithFormat:@"%3.2f%%", [myNumber doubleValue]];

And you should adjust the precision specifier (3.2) to suit the number of digits you want to display.

Upvotes: 2

Related Questions