Question

How would i set the currency in a text field to display it as a localized currency, with a leading 0. If someone types in 16.25 pence it would be formated as 0.1625£ respectively. I am using delegation and formating all text fields so only numbers can be passed in, this field should also be localized.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range     replacementString:(NSString *)string  {    // First, create the text that will end up in the     input field if you'll return YES:
    NSString *resultString = [textField.text stringByReplacingCharactersInRange:range    withString:string];
    // Now, validate the text and return NO if you don't like what it'll contain.
// You accomplish this by trying to convert it to a number and see if that worked.
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
   [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber* resultingNumber = [numberFormatter numberFromString:resultString];
    //[numberFormatter release];
    return resultingNumber != nil;   

I do not want this to change, as it formats all my fields. Just want textField1 to have the relevant format,how would i go about doing this, i think it lies in viewdidload method and setting the text property to be localized to a floating point, but i cant seem to work out how to do it.

Was it helpful?

Solution 2

  • (void)textFieldDidEndEditing:(UITextField *)textField

{ if (textfield1) {

    NSString *txt = self.textfield1.text;

    double num1 = [txt doubleValue];


    double tCost = num1 /100;





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

    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];


    NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];


    self.textfield1.text = [NSString stringWithFormat:@"%@",numberAsString];
}

}

OTHER TIPS

You can specify which textField you want to format in the delegate method above.

if (textField == textField1) {

   // Do Something....

} else {

  // Do whatever you want with the other text fields

}

For floating point formatting, use something like this -

[myTextField setText:[NSString stringWithFormat:@"%.2f", myFloat]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top