Danny Hobo
Danny Hobo

Reputation: 684

UITextField screws up after adding dots / decimals

I have my UITextField with an UIKeyboardTypeNumberPad as keyboard, so that users only can input integers. Now in order to make their input a bit more readable, I decided to add the following code:

formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
self.inputField.text = [formatter stringFromNumber:[formatter numberFromString:self.inputField.text]];

in order to change 1234 in 1,234 and so on

this works, up till the first decimal. If i comment this code out, I can put in values up till 999999999 and further if I want, but if I add this code, my text input goes like this

1 stays the same 12 stays the same 123 stays the same 1234 becomes 1,234 if i then enter an extra number (5 for example), it clears my UITextField instead of making it 12,345

how can I prevent this?

Upvotes: 0

Views: 214

Answers (2)

rmaddy
rmaddy

Reputation: 318874

When the text field has 1,234 and the user enters a 5 you end up with 1,2345 in the text field. Correct?

You then attempt to convert that string to a number using the formatter. But that's not a valid number. This is why the result becomes blank.

What you need to do is take the current text field value and strip any thousands separators and then reformat the result.

formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *separator = [formatter groupingSeparator];
// Remove any existing grouping separators from the text field text
NSString *current = self.inputField.text;
current = [current stringByReplacingOccurrencesOfString:separator withString:@""];
// Reformat the number
self.inputField.text = [formatter stringFromNumber:@([current integerValue])];

Upvotes: 2

anka
anka

Reputation: 3857

Well thats because 1,2345 is a not correctly formatted decimal number and you try to recognize it as a number. You should use instead:

NSNumberFormatter *decimalFormatter = [[NSNumberFormatter alloc] init];
[decimalFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

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

NSString *onlyNumbers = [[self.inputField.text componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];

self.inputField.text = [decimalFormatter stringFromNumber:[numberFormatter numberFromString:onlyNumbers]];

Upvotes: 1

Related Questions