Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 如何将巨大的NSDecimal格式化为字符串?_Iphone_Ios_Ipad_Nsdecimalnumber - Fatal编程技术网

Iphone 如何将巨大的NSDecimal格式化为字符串?

Iphone 如何将巨大的NSDecimal格式化为字符串?,iphone,ios,ipad,nsdecimalnumber,Iphone,Ios,Ipad,Nsdecimalnumber,获得了一个高精度的大NSDecimal。像这样: NSString *decStr = @"999999999999.999999999999"; NSDecimal dec; NSScanner *scanner = [[NSScanner alloc] initWithString:decStr]; [scanner scanDecimal:&dec]; NSDecimalNumber *decNum = [[NSDecimalNumber alloc] initWithDecim

获得了一个高精度的大
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];
output = 1,000,000,000,000

但屏幕上的输出从未正确格式化:

output = 999999999999.999999999999
我希望它有像99999999999.99999999999这样的组分离

所以我尝试了一个
NSNumberFormatter

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

NSString *output = [formatter stringFromNumber:resultDecNum];
结果是:

NSString *output = [decNum stringValue];
output = 1,000,000,000,000

有没有一种方法可以根据用户的语言环境正确地格式化高精度的NSDecimal而不丢失精度?

正如您已经注意到的,NSNumberFormatter将转换为float。 遗憾的是,只有descriptionWithLocale作为替代方案,它不能提供一种改变您想要的行为的方法。 最好的方法应该是编写自己的格式化程序,苹果甚至为此提供了一个指南:

我将以descriptionWithLocale作为起点并查找分隔符。 然后在其前面每隔3位添加comas

编辑:

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

// 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];

用另一个想法和一些(未经测试的)示例代码编辑了我下面的答案