Locale - determine whether a number will be format

2019-06-09 17:29发布

问题:

I have a question regarding this answer: https://stackoverflow.com/a/29783546/2529173

It works great, but in my app I need the user to select/change his currency. I've tried to set this with a locale like this:

class CurrencyField: UITextField {
  override func awakeFromNib() {
    super.awakeFromNib()
    addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    keyboardType = .numberPad
    textAlignment = .right
    editingChanged()
  }
  func editingChanged() {
    Formatter.currency.locale = Locale(identifier: "es_CL")
    text = Formatter.currency.string(from: (Double(string.numbers.integer) / 100) as NSNumber)
  }
}

struct Formatter {
  static let currency = NumberFormatter(numberStyle: .currency)
}

extension UITextField {
  var string: String { return text ?? "" }
}

extension String {
  var numbers: String { return components(separatedBy: Numbers.characterSet.inverted).joined() }
  var integer: Int { return Int(numbers) ?? 0 }
}

struct Numbers { static let characterSet = CharacterSet(charactersIn: "0123456789") }

extension NumberFormatter {
  convenience init(numberStyle: NumberFormatter.Style) {
    self.init()
    self.numberStyle = numberStyle
  }
}

I it's because the NumberFormatter doesn't output decimals for this currency. Is there a way to get this work?

回答1:

This is my solution for now:

class CurrencyField: UITextField {

  let locale:Locale = Locale.current

  override func awakeFromNib() {
    super.awakeFromNib()
    addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    keyboardType = .numberPad
    textAlignment = .right
    editingChanged()
  }
  func editingChanged() {
    Formatter.currency.locale = locale
    let divider:Double = pow(Double(10), Double(Formatter.currency.maximumFractionDigits))
    text = Formatter.currency.string(from: (Double(string.numbers.integer) / divider) as NSNumber)


  }
}


标签: ios swift locale