Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSNumberFormatter to insert blank space to NSString?

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?

like image 745
H3c Avatar asked Nov 20 '25 01:11

H3c


1 Answers

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).

like image 95
Nicolas Bachschmidt Avatar answered Nov 21 '25 14:11

Nicolas Bachschmidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!