Numbers and String.localizedStringWithFormat

My app uses a text field where the user enters a number. Upon an entry, the app checks to make sure that the user has entered a number and not gibberish, then stores the numerical entry as a double.


let stored = NumberFormatter().number(from: textField.text! as String)!.doubleValue


Then calculations are made and the gui updated. For updating the text field, I convert a stored double back to text:


numberInput.text = String.localizedStringWithFormat("%.\3f %@", stored, "")


It all works fine, for entries under 1000.


Problem: When a comma is inserted by the localizer, as in "1,000", and the user does not clear the entire entry or enters a comma manually - for instance edits the old entry to show "1,001" - that is no longer recognized as a number. Of course entering 1001 is fine. I cannot just strip out the comma because it can have different meanings in different locations. I want to show the comma in the textfield to propoerly format the number display.


Ideas?

Accepted Reply

With this line, you create a `NumberFormatter` with default settings, which is not documented clearly.

let stored = NumberFormatter().number(from: textField.text! as String)!.doubleValue

(And `textField.text!` is of type String, you have no need to put `as String`.)


    let nf = NumberFormatter()
    nf.numberStyle = .decimal
    //...
    if let number = nf.number(from: textField.text ?? "") {
        let stored = number.doubleValue
        //Use stored and make your calculation
        //...
    } else {
        //Do something needed when `textField.text` is not numeric
    }


I want to show the comma in the textfield to propoerly format the number display.

Better use `NumberFormatter` rather than `printf` style formatting of C-language.

        numberInput.text = nf.string(from: stored as NSNumber)

Replies

How did you configure NumberFormetter, depending on the locale ?

With this line, you create a `NumberFormatter` with default settings, which is not documented clearly.

let stored = NumberFormatter().number(from: textField.text! as String)!.doubleValue

(And `textField.text!` is of type String, you have no need to put `as String`.)


    let nf = NumberFormatter()
    nf.numberStyle = .decimal
    //...
    if let number = nf.number(from: textField.text ?? "") {
        let stored = number.doubleValue
        //Use stored and make your calculation
        //...
    } else {
        //Do something needed when `textField.text` is not numeric
    }


I want to show the comma in the textfield to propoerly format the number display.

Better use `NumberFormatter` rather than `printf` style formatting of C-language.

        numberInput.text = nf.string(from: stored as NSNumber)

No surprise, this works perfectly. Thanks!