0

I'm using the NSNumberFormatter to format currency but the formatter is not working when i use floats. However it works when I use double. i need it to work with floats as I don't need to work in double.

float t1 = 999999.99;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setAllowsFloats:YES];
[formatter setMaximumFractionDigits:2];
[formatter setAlwaysShowsDecimalSeparator:YES];
[formatter setGeneratesDecimalNumbers:YES];
NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithFloat:t1]];
NSLog(@"Output as currency: %@", formattedOutput);

this outputs - Output as currency: $1,000,000.00 and not as $9,99,999.99

Thanks in advance for your help on this.

inforeqd
  • 3,209
  • 6
  • 32
  • 46
  • 2
    *"i need it to work with floats as I don't need to work in double."* The results you are getting is specifically why it is not advisable to use floats for currencies. You _need_ to use `double` and `NSDecimalNumber`. – John Estropia May 11 '12 at 04:22
  • I see, so which one should i use... NSString *convertedAmount = [formatter stringFromNumber:[NSNumber numberWithDouble:finalAmount]]; OR NSString *convertedAmount = [formatter stringFromNumber:[NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithDouble:finalAmount] decimalValue]]]; – inforeqd May 11 '12 at 04:55
  • according to [this stackoverflow question](http://stackoverflow.com/questions/453691/how-use-nsdecimalnumber), you shouldn't use the `[NSNumber numberWith...]` way to initialize `NSDecimalNumber`s. – John Estropia May 11 '12 at 06:45

1 Answers1

1

To avoid rounding issues with floats (and doubles), for currency you should be using NSDecimalNumber's. All of your existing code listed in your question with work with them. Simply get rid of your float and use the following line instead:

NSDecimalNumber *t1 = [NSDecimalNumber decimalNumberWithString:@"999999.99"];

(Note that there are other ways to create NSDecimalNumber's, depending on how you populate your variables.)

lnafziger
  • 25,760
  • 8
  • 60
  • 101