3

得到了一个NSDecimal高精度的大。像这样:

NSString *decStr = @"999999999999.999999999999";
NSDecimal dec;
NSScanner *scanner = [[NSScanner alloc] initWithString:decStr];
[scanner scanDecimal:&dec];

NSDecimalNumber *decNum = [[NSDecimalNumber alloc] initWithDecimal:*dec];

我可以很容易地得到我的字符串表示NSDecimal

NSString *output = [decNum stringValue];

或者

NSString *output = [decNum descriptionWithLocale:nil];

但它从未正确格式化以在屏幕上输出:

output = 999999999999.999999999999

我希望它具有像 999,999,999,999.999999999999 这样的组分离

所以我尝试了一个NSNumberFormatter

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setAllowsFloats:YES];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];

NSString *output = [formatter stringFromNumber:resultDecNum];

结果是这样的:

output = 1,000,000,000,000

有没有办法NSDecimal在不丢失精度的情况下根据用户区域设置正确格式化高精度?

4

1 回答 1

1

正如您已经注意到的,NSNumberFormatter 转换为浮点数。可悲的是,只有 descriptionWithLocale 作为替代方案,它没有提供改变您想要的行为的方法。最好的方法应该是编写自己的格式化程序,Apple 甚至为此提供了指南:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/DataFormatting.html

我会以 descriptionWithLocale 为起点并寻找分隔符。然后在它之前每 3 位添加昏迷。

编辑:

另一个想法是将字符串拆分为整数部分和分隔符后面的内容,然后使用格式化程序格式化整数部分,然后将其与其余部分合并。

// Get the number from the substring before the seperator 
NSString *output = [number descriptionWithLocale:nil];
NSNumber *integerPartOnly = [NSNumber numberWithInt:[output intValue]];

// Format with decimal separators
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];

NSString *result = [formatter stringFromNumber:integerPartOnly]

// Get the original stuff from behind the separator
NSArray* components = [output componentsSeparatedByString:@"."];
NSString *stuffBehindDot = ([components count] == 2) ? [components objectAtIndex: 1] : @"";

// Combine the 2 parts
NSString *result = [result stringByAppendingString:stuffBehindDot];
于 2012-03-29T10:13:56.783 回答