本文介绍了如何防止iPhone NSNumberFormatter四舍五入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要尝试格式化大型货币数字,例如:

  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四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 03:17