NSNumberFormatter with comma decimal separator

I would recommend not hardcoding the separator to ensure the right separator behavior based on the iPhone locale setting. The easiest way to to this is: using objective-c NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init]; numberFormatter.locale = [NSLocale currentLocale];// this ensures the right separator behavior numberFormatter.numberStyle = NSNumberFormatterDecimalStyle; numberFormatter.usesGroupingSeparator = YES; // example for writing the number … Read more

NSNumberFormatter and ‘th’ ‘st’ ‘nd’ ‘rd’ (ordinal) number endings

The correct way to do this from iOS 9 onwards, is: NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; numberFormatter.numberStyle = NSNumberFormatterOrdinalStyle; NSLog(@”%@”, [numberFormatter stringFromNumber:@(1)]); // 1st NSLog(@”%@”, [numberFormatter stringFromNumber:@(2)]); // 2nd NSLog(@”%@”, [numberFormatter stringFromNumber:@(3)]); // 3rd, etc. Alternatively: NSLog(@”%@”, [NSString localizedStringFromNumber:@(1) numberStyle:NSNumberFormatterOrdinalStyle]); // 1st

Formatting a number to show commas and/or dollar sign

You should definitely use NSNumberFormatter for this. The basic steps are: Allocate, initialize and configure your number formatter. Use the formatter to return a formatted string from a number. (It takes an NSNumber, so you’ll need to convert your double or whatever primitive you have to NSNumber.) Clean up. (You know, memory management.) This code … Read more

How to input currency format on a text field (from right to left) using Swift?

For Swift 3. Input currency format on a text field (from right to left) override func viewDidLoad() { super.viewDidLoad() textField.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged) } @objc func myTextFieldDidChange(_ textField: UITextField) { if let amountString = textField.text?.currencyInputFormatting() { textField.text = amountString } } extension String { // formatting text for currency textField func currencyInputFormatting() -> String … Read more