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

StackOverflow https://stackoverflow.com/questions/23210148

  •  07-07-2023
  •  | 
  •  

Frage

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!

War es hilfreich?

Lösung

Set the currency code. Set the min and max fractions

[numberFormatter setCurrencyCode:@"USD"];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMinimumFractionDigits:0];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top