Evol Gate
Evol Gate

Reputation: 2257

Incorrect behavior of NSNumberFormatter for iOS 8

The below code outputs the correct value till iOS 7

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"0.000%;0.000%;-0.000%"];
    NSString *str = [numberFormatter stringFromNumber:@0.55368]; 

It outputs str as 55.368%

But in iOS 8 it outputs str as 1.

I don't see any deprecation or any API change in Apple's documentation of NSNumberFormatter. Is it a serious bug or am I missing something here?

Upvotes: 1

Views: 542

Answers (3)

carlodurso
carlodurso

Reputation: 2894

Evol, I run in the same issue 2 weeks ago, then I realized it was just a matter of adding

[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

That should work for you. Let me know.

Updated:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];

//[numberFormatter setPositiveFormat:@"0.000%;0.000%;-0.000%"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[numberFormatter setLocale:usLocale];
[numberFormatter setMinimumFractionDigits:3];
NSString *str = [numberFormatter stringFromNumber:@0.55368];

Upvotes: 0

combinatorial
combinatorial

Reputation: 9561

This works on iOS7 & iOS8:

numberFormatter.numberStyle = NSNumberFormatterPercentStyle;
numberFormatter.minimumFractionDigits = 3;

Upvotes: 2

Anya Shenanigans
Anya Shenanigans

Reputation: 94584

It may be an accident that this worked at all - you should have been using setFormat (which is unsupported for NSNumberFormatters), which supports the triple specification like that, with the ; separating the items.

You're supposed to use: setNegativeFormat, setPositiveFormat with the individual items e.g.

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNegativeFormat:@"-0.000%"];
[numberFormatter setPositiveFormat:@"0.000%;0.000%;-0.000%"];
NSString *str = [numberFormatter stringFromNumber:@0.55368];

Upvotes: 0

Related Questions