How to display iPhone / Objective-C currency correctly

I am trying to correctly display correctly formatted currencies from long values. I use NSNumberFormatter, but it seems to disable my decimal places where the cents will run.

For example, if I have a long value of 1203 (cents), I want it to have a fixed point format (e.g. 12.03). Here is what I did:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.numberStyle = NSNumberFormatterCurrencyStyle; formatter.currencyCode = "USD"; formatter.multiplier = [NSNumber numberWithDouble:0.01]; long currencyAmount = 1203; NSNumber *number = [NSNumber numberWithLongLong:currencyAmount]; [label setText:[formatter stringFromNumber:number]]; 

I get this release of $ 12.00, but I want $ 12.03

+4
source share
2 answers

I understood the answer. This will correctly format the long / long value in the currency.

 NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.numberStyle = NSNumberFormatterCurrencyStyle; formatter.currencyCode = "USD"; long currencyAmount = 1203; NSDecimalNumber *wrappedCurrencyAmount = [NSDecimalNumber decimalNumberWithMantissa:currencyAmount exponent:-2 isNegative:NO]; [label setText:[formatter stringFromNumber:wrappedCurrencyAmount]]; 
+1
source

Thinking about the integer cut-off error inside NSNumberFormatter is crazy speculation, but did you try the default multiplier by default and split your currency amount after converting to float by 100 yourself?

EDIT . For this workaround, the following article suggests using NSDecimalNumber to avoid rounding issues. NSNumberFormatter for formatting a currency that does not work for floats

+2
source

All Articles