user3178926
user3178926

Reputation: 339

What am I doing wrong in textfield Did End Editting?? Currency Formatting

So a part of the code looks like

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *currency = [NSNumber numberWithDouble:[self.SalesAmounttext.text doubleValue]]; 

  self.SalesAmounttext.text = [formatter stringFromNumber:currency];

}

The above code means if I enter 499 in the textfield, the text will be converted into $499.00. If I clear the ENTIRE textfield, and re-enter another number, let's say 599, the text will be converted to $599.00. These are all the correct and expected behaviours.

However, if I happen to backspace $599.00 to only $ or $5 and then enter a new number such as 509 and leave the textfield, my textfield output becomes $0.00. Does anybody know what I'm doing wrong?

Upvotes: 2

Views: 121

Answers (2)

JJC
JJC

Reputation: 1356

The doubleValue method will return 0 if you pass anything other than a valid number as the first character. From the docs:

"The floating-point value of the receiver’s text as a double. Returns HUGE_VAL or –HUGE_VAL on overflow, 0.0 on underflow. Returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number."

So you can do something like:

NSString *newString = [self.SalesAmounttext.text stringByReplacingOccurrencesOfString:@"$" withString:@""];

and pass in the newString to the formatter.

Upvotes: 1

rmaddy
rmaddy

Reputation: 318874

The problem is with:

[self.SalesAmounttext.text doubleValue]

This only gives a valid value if the text has no formatting, no currency symbol, no grouping characters, and a period for the decimal separator. If that is not all true it returns 0.

You need to convert the existing text to a double by using the currency formatter to parse the text.

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *current = [formatter numberFromString:self.SalesAmounttext.text];
    if (!current) {
        NSNumberFormatter *formatter2 = [[NSNumberFormatter alloc] init];
        current = [formatter2 numberFromString:self.SalesAmounttext.text];
    }

    self.SalesAmounttext.text = [formatter stringFromNumber:current];
}

You probably need some additional checking to deal with invalid numbers.

Upvotes: 2

Related Questions