我正在使用以下NSNumberFormatter在货币值中添加逗号和符号。
self.currencyFormatter = [NSNumberFormatter new];
self.currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
self.currencyFormatter.currencySymbol = @"£";
self.currencyFormatter.currencyCode = @"GBP";
self.currencyFormatter.roundingMode = NSNumberFormatterRoundHalfUp;
self.currencyFormatter.maximumFractionDigits = 0;
用法:
self.principleAmountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:100000]];
按预期显示100,000英镑。现在如果我在textfield中插入两个以上的数字(文本变成£100,00096)并尝试将字符串转换为Integer,我得到0!基本上后面的行返回0.我不知道如何处理这个问题。
NSLog(@"%d", [[self.currencyFormatter numberFromString:@"£100,00096"] integerValue]);
仅供参考我有自定义输入视图到文本字段,只允许数字进入文本字段。在Did Edit End中,即使我格式化数字并以逗号显示。
答案 0 :(得分:1)
您需要删除逗号以使其正常工作,您仍然可以在文本字段中显示它们,但在将字符串传递给格式化程序之前应将其删除。像这样:
NSString *userInput = @"£100,00096";
userInput = [userInput stringByReplacingOccurrencesOfString:@"," withString:@""];
NSLog(@"%ld", (long)[[currencyFormatter numberFromString:userInput] integerValue]);
答案 1 :(得分:0)
100,00096
不正确......
你的意思是其中之一吗?
[[self.currencyFormatter numberFromString:@"£10000096"] integerValue]
[[self.currencyFormatter numberFromString:@"£100,000.96"] integerValue]
[[self.currencyFormatter numberFromString:@"£100000.96"] integerValue]
[[self.currencyFormatter numberFromString:@"£10,000,096"] integerValue]
答案 2 :(得分:0)
我的参考代码。带货币符号的数字也无效!以下照顾一切。
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:@"%@%@", self.currencyFormatter.groupingSeparator, self.currencyFormatter.currencySymbol]];
self.amountTextField.text = [[self.amountTextField.text componentsSeparatedByCharactersInSet:doNotWant] componentsJoinedByString:@""];
self.amountTextField.text = [NSString stringWithFormat:@"£%@", self.amountTextField.text];
NSUInteger amount = [[self.currencyFormatter numberFromString:self.amountTextField.text] integerValue];
self.amountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:amount]]