I\'m looking for a way to format a string into currency without using the TextField hack.
For example, i\'d like to have the number \"521242\" converted into \"5,212
For Swift tested code (ref from AAV's code)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
let strMain : NSString = string
let arrTemp : NSArray = (textField.text?.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))!
let str: NSString = arrTemp.componentsJoinedByString("")
//NSInteger centAmount = cleanCentString.integerValue;
var centAmount : NSInteger = str.integerValue
if (string.length > 0)
{
// Digit added
centAmount = centAmount * 10 + strMain.integerValue;
}
else {
// Digit deleted
centAmount = centAmount / 10;
}
let amount = (Double(centAmount) / 100.0)
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = .CurrencyStyle
currencyFormatter.currencyCode = "USD"
currencyFormatter.negativeFormat = "-¤#,##0.00"
let convertedPrice = currencyFormatter.stringFromNumber(amount)
print(convertedPrice)
txtAmount.text = convertedPrice! //set text to your textfiled
return false //return false for exact out put
}
note : if you want to remove the default currency symbol from input you can use currencySymbol to blank as below
currencyFormatter.currencyCode = nil
currencyFormatter.currencySymbol = ""
Happy coding!