导致Zeros Obj C的未知错误

时间:2014-07-06 20:01:00

标签: ios currency nsnumberformatter

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

- (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;
}

View

1 个答案:

答案 0 :(得分:2)

一个问题是,fetchActualValue:方法会为您在用户界面中显示的字符串返回0f

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

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

float daysWorked = [self.daysWorkedTextField.text floatValue];

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