0

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?

Community
  • 1
  • 1
user2529173
  • 1,884
  • 6
  • 30
  • 43
  • is the question that you *do* see a decimal (when there shouldn't be one) or that you *don't* see a decimal (when there should)? – Michael Dautermann Jan 18 '17 at 04:52
  • In other currencies, EUR for example, there is a decimal and there should be one. But with the "es_CL" it seems numbers are formatted without decimals, so the code doesn't work because it divides the number by 100 which, when you enter "3", gives you "0,03" which is formatted to "$0". So the code doesn't work, because the new number never gets set. So I somehow need to determine whether a locale will show decimals or not – user2529173 Jan 18 '17 at 04:56
  • @LeoDabus yes I try to do that, but I fail to determine this. Do you know? I mean how to check the locale – user2529173 Jan 18 '17 at 05:04
  • Are you trying to let the user change it or make it always "es_CL" ? – Leo Dabus Jan 18 '17 at 05:14
  • I let the user change it – user2529173 Jan 18 '17 at 05:15

1 Answers1

0

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)


  }
}
user2529173
  • 1,884
  • 6
  • 30
  • 43