Search code examples
objective-cnsnumberformatter

NSNumberFormatterCurrencyStyle where decimals are only shown when period is used on the keypad


I am a new obj c programmer, and I haven't figured out what condition to switch for the following scenario:

That is to say, if user types "1", then the fee will be "$1", if user types "1" then "2", the fee will be "$12", if user types "1" "2" then "3", the fee will be "$123". The user will need to manually type in decimal if they want there to be any cents.

I am using UITextField as the input field. Part of my code:

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];

    cell.input = [[UITextField alloc] initWithFrame:CGRectMake(0, 6, cell.frame.size.width, 80)];
    cell.input.currencyNumberFormatter = numberFormatter; 

Would I place the condition in the UITextField method:

  • (void)textFieldDidBeginEditing:(UITextField *)textField {}

Any hint you can provide would be really appreciated. Thank you!


Solution

  • Set the currency code. Set the min and max fractions

    [numberFormatter setCurrencyCode:@"USD"];
    [numberFormatter setMaximumFractionDigits:2];
    [numberFormatter setMinimumFractionDigits:0];