I want to write a UITextField that can auto format a number to bank number.
For example: Input 1234567890098765 will be automatically displayed as 1234 5678 9009 8765.
I'll use textFieldDelegate to do it, but I don't know how to use NSNumberFormatter.
How can I do it?
Using NSNumberFormatter is simple.
NSNumber *number = [NSNumber numberWithLongLong:1234567890098765];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setUsesGroupingSeparator:YES];
[formatter setGroupingSize:3];
// [formatter setGroupingSeparator:@"\u00a0"];
NSString *string = [formatter stringFromNumber:number];
I deliberately commented the line that sets the formatter's grouping separator as it may be better to use the default one, which is provided by the user's locale (e.g. , in the USA, . in Germany and ' in Switzerland). Also please note that iOS doesn't use a space as a separator but a non-breaking space (U+00A0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With