NSNumberFormatter for formatting a currency that does not work for floats

I use NSNumberFormatter to format the currency, but formatting does not work when I use float. However, it works when I use double. I need it to work with floats, since I do not need to work in dual mode.

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); 

these exits are currency exits: $ 1,000,000.00 and not $ 9,99,999.99

Thanks in advance for your help.

0
source share
1 answer

To avoid rounding issues with float (and double), you must use NSDecimalNumber for currency. All your existing code referenced in your question works with them. Just get rid of your float and use the following line:

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

(Note that there are other ways to create an NSDecimalNumber, depending on how you populate the variables.)

+1
source

All Articles