我以货币形式输入,例如 54 转换为 0.54,但是当我尝试输入 100 时,我只以 0.1 的形式输出。代码不适用于0
. 您不能将值输入为100.00
。我使用的代码是
(BOOL)textField:(UITextField *)transactionAmount shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
NSString *substring = transactionAmount.text;
substring = [substring stringByAppendingString:string];
NSLog(@"Text : %@",substring);
NSString *cleanCentString = [[transactionAmount.text
componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:@""];
// Parse final integer value
NSInteger centAmount = cleanCentString.integerValue;
// Check the user input
if (string.length > 0)
{
// Digit added
centAmount = centAmount * 10 + string.integerValue;
}
else
{
// Digit deleted
centAmount = centAmount / 10;
}
// Update call amount value
NSNumber *amount = [[NSNumber alloc] initWithFloat:(float)centAmount / 100.0f];
// Write amount with currency symbols to the textfield
NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init];
// [_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[_currencyFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[_currencyFormatter setCurrencyCode:@"USD"];
[_currencyFormatter setNegativeFormat:@"-¤#,##0.00"];
self.transactionAmount.text = [_currencyFormatter stringFromNumber:amount];
// [self SetMainMessage:customTipsValue.text];
return NO;
}