问题描述
我要尝试格式化大型货币数字,例如:
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]);
忽略Locale的影响一会儿,我发现我一直得到以下输出,舍入:
1,000,000,000,000,000,000
b $ b
我期望:
999,999,999,999,999,993
我试过改变舍入没有效果。为什么 NSNumberFormatter
坚持舍入?
NSNumberFormatter
在显示之前将数字转换为double,这不是你想要的。 NSDecimalNumber
有一个符合您需要的 descriptionWithLocale:
方法。
请参阅以下答案:
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?
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
这篇关于如何防止iPhone NSNumberFormatter四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!