You can use this code:
func currencyStringFromNumber(number: Double) -> String {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)
return formatter.stringFromNumber(number)
}
let currencyString = currencyStringFromNumber(21010)
println("Currency String is: \(currencyString)")
// Will print $21,010.00
Here's a compilable and working example of this information extrapolated to work as you require.
import UIKit
class CurrencyTextFieldExample: UIViewController {
let currencyFormatter = NSNumberFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let textField = UITextField()
textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
textField.frame = CGRect(x: 0, y: 40, width: 320, height: 40)
textField.keyboardType = UIKeyboardType.NumberPad
textField.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(textField)
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
currencyFormatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidChange(textField: UITextField) {
var text = textField.text.stringByReplacingOccurrencesOfString(currencyFormatter.currencySymbol, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.groupingSeparator, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.decimalSeparator, withString: "")
textField.text = currencyFormatter.stringFromNumber((text as NSString).doubleValue / 100.0)
}
}
Let me know if you have questions.