如何在计算中使用货币值

时间:2014-07-28 20:28:25

标签: swift

我有一个存储我需要在计算中使用的货币值的变量,但我无法弄清楚如何在计算中使用它,因为变量在其开头有一个货币符号(例如£ 2.43,$ 70.82,€300.21)。我已经考虑过用零替换第一个字符,但是这不起作用,因为有些货币使用多个字符而有些货币在值之后有符号。

有没有人知道除了值本身之外如何删除所有字符?或者将变量转换为计算的另一种方法? (我顺便使用Swift)

编辑:

我一直在尝试使用NSDecimalNumber来转换字符串,但是我收到错误'NSNumber不能转换为NSDecimalNumber'。这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

您可以使用以下问题代码:

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)

要做到这一点:

func currencyStringAsDouble(currencyString: String) -> Double {
    let cleanedString = currencyString.stringByReplacingOccurrencesOfString(currencyFormatter.currencySymbol, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.groupingSeparator, withString: "").stringByReplacingOccurrencesOfString(currencyFormatter.decimalSeparator, withString: "")
    let currencyDouble = (text as NSString).doubleValue / 100.0
    return currencyDouble;
}