您好,我需要格式化用户在应用程序中输入的十进制数。
100. = 100
90.00 = 90
90.1 = 90.1
90.22 = 90.22
90.227 = 90.23
我应该如何使用 NSNumberFormatter来实现这一点。
我使用此自定义如果其他条件实现了相同的目标
if ([cell.textField.text rangeOfString:@"."].location != NSNotFound)
{
NSString *strAfterDecimal = [cell.textField.text componentsSeparatedByString:@"."].lastObject;
NSInteger count = [strAfterDecimal length];
if(count == 0)
{
customField.value = [cell.textField.text
stringByReplacingOccurrencesOfString:@"." withString:@""];
}
else if(count == 1 || count == 2)
{
if([strAfterDecimal integerValue] > 0)
{
customField.value = cell.textField.text;
}
else
{
customField.value = [cell.textField.text componentsSeparatedByString:@"."].firstObject;
}
}
else if(count > 2)
{
if([strAfterDecimal integerValue] > 0)
{
customField.value = [NSString stringWithFormat:@"%0.2f",[cell.textField.text floatValue]];
}
else
{
customField.value = [cell.textField.text componentsSeparatedByString:@"."].firstObject;
}
}
}
我需要调整代码的大小。根据客户的说法,如果苹果提供的默认功能可以执行操作,我无法输入额外的代码
这非常简单
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSNumber *number = [formatter numberFromString:cell.textField.text];
NSString *numberString = [formatter stringFromNumber:number];
if (numberString == nil) numberString = @"0";
NSLog(@"%@", numberString);
Swift 版本有点复杂,因为您必须安全地解开选项。
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
let numberString : String
if let text = cell.textField.text,
let number = formatter.number(from: text),
let string = formatter.string(from: number) {
numberString = string
} else {
numberString = "0"
}
print(numberString)