我找到了下面的代码,我正在尝试在UITableView shouldChangeCharactersInRange事件中工作。没有货币符号,它可以正常工作。
当我尝试添加货币符号时,它只允许我输入一个数字。它应该做的是,比如我输入7536,它应该出现在以下步骤:£0.07,£0.75,£7.53,£75.36,但它显示为£0.07,£0.05,£0.03,£0.06
继承代码。
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{ BOOL res = TRUE;
double currentValue = [textField.text doubleValue];
double cents = round(currentValue * 100.0f);
if ([string length]) {
for (size_t i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (isnumber(c)) {
cents *= 10;
cents += c - '0';
}
}
} else {
// back Space
cents = floor(cents / 10);
}
// This line next works without the currency symbol
//textField.text = [NSString stringWithFormat:@"%.2f", cents / 100.0f];
NSMutableString *aString = [NSMutableString stringWithFormat:@"%@", strCurrencySymbol];
[aString appendFormat:@"%.2f", cents / 100.0f];
textField.text = aString;
res = NO;
return res;
}
答案 0 :(得分:0)
[@"£1.23" doubleValue]
为0.如果有一个货币符号,您必须跳过一个主要货币符号,例如:
NSString * currentText = textField.text;
NSRange range = [currentText rangeOfString:strCurrencySymbol];
if (range.location == 0)
{
currentText = [currentText substringFromIndex:range.length];
}
double currentValue = [currentText doubleValue];
一般来说,我建议不要做这样的事情:
答案 1 :(得分:0)
NSCharacterSet *currencySet = [NSCharacterSet characterSetWithCharactersInString:@"$€£¥"];
NSMutableString *strSource = [NSMutableString stringWithString:textField.text];
if (![strSource isEqualToString:@""]) {
[strSource replaceCharactersInRange: [strSource rangeOfCharacterFromSet:currencySet] withString:@""];
}
double currentValue = [strSource doubleValue];
double cents = round(currentValue * 100.0f);
if ([string length]) {
for (size_t i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (isnumber(c)) {
cents *= 10;
cents += c - '0';
}
}
} else {
// back Space
cents = floor(cents / 10);
}
NSMutableString *aString = [NSMutableString stringWithFormat:@"%@", strCurrencySymbol]; // does not need to be released. Needs to be retained if you need to keep use it after the current function.
switch (intDecimalPlaces) {
case 0:
[aString appendFormat:@"%.0f", cents / 100.0f];
break;
case 1:
[aString appendFormat:@"%.1f", cents / 100.0f];
break;
case 2:
[aString appendFormat:@"%.2f", cents / 100.0f];
break;
case 3:
[aString appendFormat:@"%.3f", cents / 100.0f];
break;
default:
break;
}
textField.text = aString;
我忘了在开始时删除货币符号。 然后你最后添加它没有问题。