在 iphone sdk 中使用 NSNumberFormatter 和 NSDecimalNumberHandler
作为我正在做的格式化非常大、精确的数字的快速测试:
(number is a synthesized NSDecimalNumber...) number = [[NSDecimalNumber alloc] initWithDecimal:[[NSDecimalNumber numberWithDouble:420000008698643507200000.0F] decimalValue]]; DLog(@"unformatted: %@", [number stringValue]);
这给了我:“未格式化:420000008698643507200000”
,但是当我尝试通过 NSNumberFormatter
格式化它时,它非常不对......舍入方式或其他...
numFormatter = [[NSNumberFormatter alloc] init]; [numFormatter setNumberStyle:kCFNumberFormatterDecimalStyle]; [numFormatter setRoundingMode:kCFNumberFormatterRoundDown]; [numFormatter setMaximum:nil]; DLog(@"formatted: %@", [numFormatter stringFromNumber:number]);
给我:“formatted: 420,000,008,698,644,000,000,000”
我希望有一些我没有看到的秘密 NSNumberFormatter
魔法属性,但我尝试了 setUsesSignificantDigits
并且setMaximumSignificantDigits
,但这似乎不起作用。
有人有主意吗? 非常感谢!
as a quick test of formatting very large, precise numbers i'm doing:
(number is a synthesized NSDecimalNumber...) number = [[NSDecimalNumber alloc] initWithDecimal:[[NSDecimalNumber numberWithDouble:420000008698643507200000.0F] decimalValue]]; DLog(@"unformatted: %@", [number stringValue]);
which gives me: "unformatted: 420000008698643507200000"
but when i try to format it via NSNumberFormatter
, it's quite off... rounding way up or something...
numFormatter = [[NSNumberFormatter alloc] init]; [numFormatter setNumberStyle:kCFNumberFormatterDecimalStyle]; [numFormatter setRoundingMode:kCFNumberFormatterRoundDown]; [numFormatter setMaximum:nil]; DLog(@"formatted: %@", [numFormatter stringFromNumber:number]);
gives me: "formatted: 420,000,008,698,644,000,000,000"
i'm hoping there's some secret NSNumberFormatter
magic property that i'm not seeing, but I tried setUsesSignificantDigits
and setMaximumSignificantDigits
, but that didn't seem to work.
anyone have any ideas? thanks a bunch!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的精度损失来自于
NSNumberFormatter
将数字转换为双精度的事实。您是否考虑过使用
NSDecimalNumber的descriptionWithLocale:
方法? 作为起点,您只需传入[NSLocale currentLocale]
作为参数即可。 然后,您可以开始通过 NSLocaleDecimalSeparator 和 NSLocaleGroupingSeparator 来使用区域设置配置。Your loss of precision comes from the fact that
NSNumberFormatter
converts the number to a double.Have you considered using
NSDecimalNumber's descriptionWithLocale:
method? As a starting point you could just pass in[NSLocale currentLocale]
as a param. Then you can start playing with the locale configuration viaNSLocaleDecimalSeparator
andNSLocaleGroupingSeparator
.