I have a variable that stores a currency value that I need to use in a calculation, however I can't figure out how to use it within a calculation as the variable has a currency symbol at the start of it (e.g. £2.43, $70.82, €300.21). I have thought about replacing the first character with nothing however this won't work because some currencies use more than one character and some have the symbol after the value.
Does anyone know how I can remove all characters with the exception of the value itself? Or another way to get the variable into a calculation? (I am using Swift by the way)
EDIT:
I've been trying NSDecimalNumber to convert the string however I am getting the error 'NSNumber is not convertible to NSDecimalNumber'. This is the code I have:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
resetButtonNav.enabled = false
self.navigationController.navigationBar.barTintColor = UIColor.newBlueColor()
self.tabBarController.tabBar.selectedImageTintColor = UIColor.newBlueColor()
UINavigationBar.appearance().barTintColor = UIColor.newBlueColor()
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
self.view.addSubview(textField)
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
currencyFormatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)
}
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)
}
@IBAction func enterBudgetButton(sender : AnyObject) {
finalUserBudget = textField.text
budgetName = budgetNameText.text
var currencyFormatterTest:NSNumberFormatter
currencyFormatterTest.formatterBehavior = NSNumberFormatterBehavior.Behavior10_4
currencyFormatterTest.generatesDecimalNumbers = true
currencyFormatterTest.numberStyle = NSNumberFormatterStyle.CurrencyStyle
var finalUserBudgetFormatted: NSDecimalNumber = currencyFormatter.numberFromString(finalUserBudget)
}