简体   繁体   English

格式化后从文本字段中获取双值

[英]Get value from textfield as double after formatting

I was wondering if someone could shed me some light on the following: I have a textfield which formats itself to a currency format (so it displays nicely for the user), as such, eg $100,000,000.00. 我想知道是否有人可以向我说明以下几点:我有一个文本字段,将其自身格式化为货币格式(因此对用户显示很好),例如$ 100,000,000.00。 And I need that as a double, I've tried a few things and the best I've come up with was converting to a double but then obtaining 10.0 from the example above, instead of the full 100000000.00. 我需要将其作为双精度对象,我已经尝试了一些方法,并且我想出的最好的方法是转换为双精度对象,但是从上面的示例中获得了10.0,而不是完整的100000000.00。 I would really appreciate if you guys could help me out! 如果你们能帮助我,我将不胜感激! Thank you! 谢谢!

class MainScreen: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboard()

    moneySpentTextField.addTarget(self, action: #selector(moneySpentTextFieldDidChange), for: .editingChanged)
    moneySpentTextField.delegate = self
}

@objc func moneySpentTextFieldDidChange(_ textField: UITextField) {
    if let amountString = moneySpentTextField.text?.currencyInputFormatting() {
        moneySpentTextField.text = amountString
    }
}

extension String {

// formatting text for currency textField
func currencyInputFormatting() -> String {

    var number: NSNumber!

    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.locale = Locale.current

    var amountWithPrefix = self

    // remove from String: "$", ".", ","
    let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
    amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count), withTemplate: "")

    let double = (amountWithPrefix as NSString).doubleValue
    number = NSNumber(value: (double / 100))

    // if first number is 0 or all numbers were deleted
    guard number != 0 as NSNumber else {
        return "$0"
    }

    return formatter.string(from: number)!
}
var i = "$100,000,000.00"
var number: NSNumber!

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current


// remove from String: "$", ".", ","
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
var amountWithPrefix = regex.stringByReplacingMatches(in: i, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, i.count), withTemplate: "")

let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 100))

// if first number is 0 or all numbers were deleted
print(number)

output:100000000 输出:亿

Your code is correct. 您的代码是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM