views:

800

answers:

1

Hi, I'm trying to format large currency numbers like this:

NSNumber *testVal = [NSDecimalNumber decimalNumberWithString: @"999999999999999993.00"];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setMaximumIntegerDigits:19];
[formatter setMaximumFractionDigits:0];
NSNumberFormatter *formatter = [Formatters numberFormatterForField:f];
NSLog([formatter stringFromNumber:testVal]);

Ignoring the effect of Locale for a moment, I find that I consistently get the following output regardless of the rounding:

1,000,000,000,000,000,000

I expect:

999,999,999,999,999,993

I've tried changing the rounding with no effect. Why does NSNumberFormatter insist on rounding up?

+3  A: 

NSNumberFormatter converts the number to a double before displaying, so that's not what you want. NSDecimalNumber has a descriptionWithLocale: method that should suit your needs.

See this answer: link

rpetrich
Actually, in my original code I'm given a double and need to format that. I had just switched to trying NSDecimalNumber to see if it made any difference (and it doesn't). I guess there's no way to avoid this loss of precision when NSNumberFormatter converts from a double to a string?
thrusty
Doubles only have roughly 17-18 decimal digits of precision to begin with: http://cboard.cprogramming.com/c-programming/93742-extended-vs-double-precision.html NSNumberFormatter cannot recover information that has already been lost
rpetrich