3

I am trying to properly display properly formatted currencies from long values. I am using NSNumberFormatter however it seems to be cutting off my decimal places where the cents would go.

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

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 am getting this output $12.00 but I want $12.03

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
thunderousNinja
  • 3,510
  • 9
  • 37
  • 49

2 Answers2

2

To think of an integer cut-off bug inside of NSNumberFormatter is crazy speculation but have you tried the default multiplier of one and dividing your currency amount after conversion to float by 100 yourself?

EDIT: For this workaround the following post suggests the use of NSDecimalNumber to avoid rounding problems. NSNumberFormatter to format currency not working for floats

Community
  • 1
  • 1
s.bandara
  • 5,636
  • 1
  • 21
  • 36
1

I figured out the answer. This will properly format a long/long long value to a 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]];
thunderousNinja
  • 3,510
  • 9
  • 37
  • 49