如何使用函数最小化重复代码?

时间:2014-02-05 20:00:50

标签: ios objective-c

float qwer4 = 0;

NSNumberFormatter *eFormatter = [[NSNumberFormatter alloc] init];

[eFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];

[eFormatter setMaximumFractionDigits:0];

NSString *formattede = [eFormatter stringFromNumber:[NSNumber numberWithFloat:qwer4]];

self.eLabel.text = [NSString stringWithFormat:@"%@",formattede];//





float qwer6 = qwer4*6/100; 

NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];

[pFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];

[pFormatter setMaximumFractionDigits:0];

NSString *formattedpTax = [pFormatter stringFromNumber:[NSNumber numberWithFloat:qwer6]];

self.pLabel.text = [NSString stringWithFormat:@"%@",formattedp];




NSNumberFormatter *tFormatter = [[NSNumberFormatter alloc] init];

[tFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];

[tFormatter setMaximumFractionDigits:0];

NSString *formattedtTax = [tTaxFormatter stringFromNumber:[NSNumber numberWithFloat:qwer4 + qwer6]];

self.tLabel.text = [NSString stringWithFormat:@"%@",formattedt];
  • (无效)重复 { NSNumberFormatter * tFormatter = [[NSNumberFormatter alloc] init];

    [tFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    [tFormatter setMaximumFractionDigits:0];

    NSString * formattedt = [tTaxFormatter stringFromNumber:[NSNumber numberWithFloat:??]];

    self.tLabel.text = [NSString stringWithFormat:@“%@”,formattedt]; }

1 个答案:

答案 0 :(得分:0)

仅创建一个NSNumberFormatter对象并在所有三个位置使用它。这将缩短您的代码并使其看起来更清晰。