Skip navigation.
 
mlNSNumberFormatterPercentStyle flakiness
FROM : Aron Nopanen
DATE : Sun Jun 15 14:22:04 2008

Hi,

I've noticed some odd behavior with NSNumberFormatterPercentStyle in 
NSNumberFormatter (on Leopard 10.5.3).  Attempting to translate an 
invalid string to a number causes subsequent number-to-string 
conversions to give invalid results.  'Invalid results' can be more 
accurately defined as 'correct value * 100'.

The following brief example illustrates.  First, I create a number 
formatter with 'percent' style.  It translates '0.01' to string "1%". 
I then try to translate an invalid string ("blah"; anything will do) 
to a number.  Finally, I again translate '0.01' to a string, and get 
"100%" instead.

I've tried setting the multiplier to '1', which gives the same results 
with the decimal point shifted two places to the left.  I verified in 
the debugger that the formatter attributes don't change during program 
execution.

Localization is English, New Zealand.  English, United States gives 
the same results.

Source and output follow.  Any ideas?

Regards,
Aron

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

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

   [nf setNumberStyle:NSNumberFormatterPercentStyle];

   // Get string value for 0.01; results in 1%
   NSNumber *num = [NSNumber numberWithFloat:0.01];
   NSLog(@"\"%@\" gives \"%@\"", num, [nf stringFromNumber:num]);

   // Attempt to translate any invalid string
   NSString *str = @"blah", *err;
   id obj = nil;
   [nf getObjectValue:&obj forString:str errorDescription:&err];
   NSLog(@"String \"%@\" gives \"%@\" error \"%@\"", str, obj, err);

   // Get string value for 0.01, again; results in 100%
   NSLog(@"\"%@\" gives \"%@\"", num, [nf stringFromNumber:num]);

   [nf release];
   [pool drain];
   return 0;
}

Output:

2008-06-16 00:13:20.094 NumberFormatterPlay[13343:10b] "0.01" gives "1%"
2008-06-16 00:13:20.108 NumberFormatterPlay[13343:10b] String "blah" 
gives "(null)" error "Formatting error."
2008-06-16 00:13:20.108 NumberFormatterPlay[13343:10b] "0.01" gives 
"100%"

Related mailsAuthorDate
mlNSNumberFormatterPercentStyle flakiness Aron Nopanen Jun 15, 14:22
mlRe: NSNumberFormatterPercentStyle flakiness Deborah Goldsmith Jun 20, 00:05