2

I am working on an iOS app that requires the user to enter a dollar amount. It needs to allow them to enter dollars and cents with a max value of $9999.99

I want it to work like this: there is a textfield that displays: "$0.00" to type $5.25 the input will change with each key press. so it would look like this: '5' is pressed, display: $0.05 '2' is pressed, display: $0.52 '5' is pressed, display: $5.25

I have tried to make this work a number of different ways but all present the problem. Using NSNumberformatter does not work correctly. Using a link list or array will not work if the user presses backspace, and I really do not want to implement a stack as I fear it will be too time consuming. Please advise on how I should approach this problem. Thanks

Tanner Ewing
  • 337
  • 4
  • 18

2 Answers2

1

This is just an indicative example that shows how to do it. You should study this code and readapt it to your situation. Try it:

@autoreleasepool
{
    // Here I create the formatter and I set the format. You do this faster with setFormat: .
    NSNumberFormatter* formatter=[[NSNumberFormatter alloc]init];
    formatter.numberStyle= NSNumberFormatterCurrencyStyle;
    formatter.maximumIntegerDigits=6;
    formatter.maximumFractionDigits=2;
    formatter.currencySymbol= @"$";
    formatter.currencyDecimalSeparator= @".";
    formatter.currencyGroupingSeparator= @",";
    formatter.positivePrefix=@"";

    NSArray* numbers= @[ @1 ,@2 ,@3 ,@4, @5, @6, @7, @8  ];
    // These are the inserted numbers, you should change the code in a way that
    // every number is taken in input from the text field.
    float number=0.0f;
    for(NSUInteger i=0;i<8;i++)
    {
        // It just simulates what happens if the user types the numbers in the array.
        number= [numbers[i] floatValue] * 1.0e-2 + number*10;
        NSLog(@"%@",[formatter stringFromNumber: @(number)]);
    }
}
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
0
NSString* formattedAmount = [NSString stringWithFormat:@"$%01d.%02d",dollars,cents];
Hot Licks
  • 47,103
  • 17
  • 93
  • 151