Question

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!?

Was it helpful?

Solution

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%.

OTHER TIPS

Just set the multiplier to 1 if your numbers are already in percentage.

numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
[numberFormatter setMaximumFractionDigits:0];
[numberFormatter setMultiplier:@1];

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 (‱).

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%.

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.

Pulkit Goyal's Answer is correct...setting the multiplier to 1 makes '50' into '50%'

Swift 4/5

Create NSNumber extension just like this

extension NSNumber {
    func getPercentage() -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .percent
        formatter.maximumFractionDigits = 0 // You can set what you want
        return formatter.string(from: self)!
    }
}

Get percentage

let confidence = 0.68300 as NSNumber
print(confidence.getPercentage())

Output

68%

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top