views:

90

answers:

4

I don't understand how NSNumberFormatterPercentStyle works!

Example:

NSNumber *number = [NSNumber numberWithFloat:90.5];
NSNumberFormatter *percentageFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[percentageFormatter setNumberStyle:NSNumberFormatterPercentStyle];

NSString *strNumber = [percentageFormatter stringFromNumber:numbericString];
NSLog (strNumber);  // Output: 9,050%

I simply want to show "90.5%" (respecting NSLocal). What is NSNumberFormatterPercentStyle doing with 90.5, and why? And, how can i get my desired result!?

+7  A: 

Its presuming that the number is in the range of 0-1, as it is a percent

so 0.905 would get you 90.5%.

John Gardner
+2  A: 

I do not know that language, but based on your code sample and output, I would guess that the percentage formatter multiplies by 100 and then puts the % sign on so that 1 becomes 100%. What you want is to use .905, which should become 90.5%.

murgatroid99
+1  A: 

The "percent style" formatter expects a number of 0.905 if you want to end up with 90.5%. It interprets 90.5 as out of 1, so it's 9050% of 1.

jtbandes
+1  A: 

Let's start with the basics:

  • 1 = 100%
  • 1/2 = 0.5 = 50%

"Percent" means "out of 100", so 12% means 12/100. You don't "multiply by 100" to get a percentage value, you multiply by 100% (which is the same as multiplying by 1, which is the same as not doing anything).

Not everyone uses base 10 (though most "modern" languages do), and not everyone uses 100 as a denominator. See, for example, perMillSymbol (or kCFNumberFormatterPerMillSymbol). There's no "permill" format, but it's possible that it's automatically used for locales which don't use percentages.

See also: PER MILLE SIGN (‰) and PER TEN THOUSAND SIGN (‱).

tc.