Search code examples
iosxcodetextfieldcurrency

adding decimals and american currency symbol to single view app


First off, I want to thank the developers and programmers on the site who have answered many of my questions in the past. It wasn't until today that I signed up at stackoverflow. The answers many of you have provided to others has helped me a lot! Thank you!

I have an app that I am working on that takes a daily rate of pay multiplies it by days worked and then by the federal tax percentage and gives the user a net income and a gross income amount.

The issue I am having is that I cannot figure out how to implement the '$" in my net & gross income textfields.

Secondly, I would like to express that I am a total NOOB at this, so I apologize that this question may render you to say "Ha, really Josh? This is coding for 9 year olds!" I copied some code from an earlier post and implanted it into mine, so it may seem off. If you can take a look at the code and tell me what I need to do, I would greatly appreciate it! Thanks!

@implementation CRPDViewController
@synthesize dailyRateTextField;
@synthesize daysWorkedTextField;
@synthesize grossIncomeTextField;

- (IBAction)calculateButtonPressed:(UIButton *)sender
{
    int result = [dailyRateTextField.text intValue] * [daysWorkedTextField.text intValue];
    grossIncomeTextField.text = [NSString stringWithFormat:@"%.d", result];
    float taxRate = .72;
    float grossPay = [self.grossIncomeTextField.text floatValue];
    float netPay = grossPay * taxRate;
    self.netIncomeTextField.text = [NSString stringWithFormat:@"%.f", netPay];

    // alloc formatter
    NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];

    // set options.
    [currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSNumber *amount = [NSNumber numberWithInteger:78000];

    // get formatted string
    NSString* netPay = [currencyStyle stringFromNumber:amount]

    [currencyStyle release];

}

Please give explanations in laymen terms as much as possible! Thanks Again! :)

Joshua Hart


Solution

  • To set only the $ sign use:

    [NSString stringWithFormat:@"$%.f", netPay];
    

    and setting floating point to 2 decimal places try something like:

     self.netIncomeTextField.text = [NSString stringWithFormat:@"$%.2f", netPay];