禁用NSNumberFormatter的语言环境

时间:2014-08-15 05:17:39

标签: ios objective-c

我使用格式为“##,## 0.00”的NSNumberFormatter,但我的语言环境设置为南非地区,使用的货币格式为“## ## 0.0”,有没有办法让我禁用NSNumberFormatter使用区域设置,并具体使用我输入的格式?我试着去试试:

formatter.locale = nil;

formatter.formatterBehavior = NSNumberFormatterNoStyle;

我程序的一些输出:

format =#,## 0.00

结果= -8 933 434,38

有一个变量

formatter.localizesFormat = NO;

但这仅适用于OS X

服务器将告诉我要使用的数字格式,并且需要覆盖用户将其区域设置为的内容。

相关代码:

self.amountFormat = @"##,##0.00";

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
NSLog(@"self.amountFormat = %@", amountFormat);
[formatter setNumberStyle:NSNumberFormatterNoStyle];
[formatter setPositiveFormat: self.amountFormat];
[formatter setLenient:YES];

NSNumber* newNumber = [NSNumber numberWithDouble: [number doubleValue] / 100.0];

NSString* numberString = [formatter stringFromNumber: newNumber];

NSLog(@"numberString = %@",numberString);

输出

[Currency.m:64] self.amountFormat = ##,##0.00
[Currency.m:73] numberString = 1 533 434,34

如果您想测试

,请将一般 - 国际 - 地区格式下的设置更改为南非

3 个答案:

答案 0 :(得分:8)

对于格式化字符串,,表示grouping separator.表示由区域设置非文字字符指定的decimal separator。见the format specification
要覆盖它,您必须指定grouping separator,decimal separator.的区域设置,例如en_US_POSIX

[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];

或手动指定grouping separatordecimal separator,如:

[formatter setGroupingSeparator:@","];
[formatter setDecimalSeparator:@"."];

答案 1 :(得分:0)

由于rintaro answer建议你必须添加grouping separatordecimal separator

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterNoStyle];
[formatter setPositiveFormat:@"#,##0.00"];
[formatter setGroupingSeparator:@","]; //This line taken from above answer
[formatter setDecimalSeparator:@"."]; //This line taken from above answer
[formatter setLenient:YES];
NSString *str = [formatter stringFromNumber:@123414231412.45];
NSLog(@"%@",str);

控制台输出

2014-08-15 11:28:59.075 TestApp[700:60b] 123,414,231,412.45

答案 2 :(得分:0)

-(NSString *)amount:(NSString *)val{
    NSNumber *someNumber = [NSNumber numberWithDouble:[val doubleValue]];
    NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
    [nf setNumberStyle:NSNumberFormatterCurrencyStyle];
    // if you want to add the  custom currency than you need to specify otherwise it will take the $ USD currency. here you have to pass the string with valid string amount without ex: 135.21 (Valid), 13,2000.00 (Invalid), $123 (Invalid).
    return  [nf stringFromNumber:someNumber];
}