区域设置 - 确定是否使用小数格式化数字

时间:2017-01-18 04:47:02

标签: ios swift locale

我对此答案有疑问:https://stackoverflow.com/a/29783546/2529173

效果很好,但在我的应用中,我需要用户选择/更改其货币。我尝试使用这样的语言环境来设置它:

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

我是因为NumberFormatter没有输出这种货币的小数。有没有办法让这项工作?

1 个答案:

答案 0 :(得分:0)

这是我现在的解决方案:

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)


  }
}