导致零的未知错误

导致零的未知错误

我的代码似乎正确,但是由于某种原因,在字段中输入数字后,每个文本字段(工作天数除外)都变为零。有人可以看看下面的代码,看看我可能做错了什么吗?

- (IBAction)calculateButtonPressed:(UIButton *)sender
{
    float bonusRate = [self fetchActualValue:self.bonusTextField.text];
    float deductionsRate = [self fetchActualValue:self.deductionTextField.text];
    float dailyRate = [self fetchActualValue:self.dailyRateTextField.text];
    float daysWorked = [self fetchActualValue:self.daysWorkedTextField.text];
    float grossPay = dailyRate * daysWorked + bonusRate;
    float taxRate = .72;
    float ssRate = .0620;
    float medRate = .0145;
    float medgrossrate = grossPay * medRate;
    float ssgrossrate = grossPay * ssRate;
    float nillRate = 1;
    float bonusTax = .75;
    float bonusLeft = bonusRate * bonusTax;
    float net = medgrossrate + ssgrossrate;
    if (medTaxSwitchOutlet.on) medRate = medRate;
    else medRate = nillRate;
    if (ssTaxSwitchOutlet.on) ssRate = ssRate;
    else ssRate = nillRate;
    if (fedTaxSwitchOutlet.on) taxRate = taxRate;
    else taxRate = nillRate;

    float netPay = grossPay * taxRate + bonusLeft - net - deductionsRate;
    self.dailyRateTextField.text = [self fetchFormattedTextValue:dailyRate];
    self.netIncomeTextField.text = [self fetchFormattedTextValue:netPay];
    self.grossIncomeTextField.text = [self fetchFormattedTextValue:grossPay];
    self.bonusTextField.text = [self fetchFormattedTextValue:bonusRate];
    self.deductionTextField.text = [self fetchFormattedTextValue:deductionsRate];
}
- (NSString*)fetchFormattedTextValue:(float)value{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
    NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
    return numberAsString;
}

- (float)fetchActualValue:(NSString*)strValue{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
    float num = [[numberFormatter numberFromString:strValue] floatValue];
    return num;
}

最佳答案

一个问题是fetchActualValue:方法将为您在UI中显示的字符串返回0f

float daysWorked = [self fetchActualValue:self.daysWorkedTextField.text];

上面的行将“工作天数”文本字段中的字符串(在您的情况下为@"28"字符串)传递给fetchActualValue:方法。我怀疑原因是该方法仅解析符合数字样式NSNumberFormatterCurrencyStyle的数字。对于工作日的计算,请尝试仅将floatValue消息发送到daysWorkedTextField.text。也就是说,将以上行替换为:
float daysWorked = [self.daysWorkedTextField.text floatValue];

我还要补充两点-通常,格式化程序上的数字样式和日期样式应用于格式化输出给用户的格式,但是使用它们格式化输入可能会容易出错。另外,将浮点数用于财务计算是highly discouraged

关于ios - 导致零的未知错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24599810/

10-10 19:08