Search code examples
swiftlocalizationnsnumbernumberformatter

In Swift 5, How to convert a Float to a String localized in order to display it in a textField?


I need to convert a Float to a localized String. i write this function which is an extension from Float:

 func afficherUnFloat() -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        numberFormatter.locale = Locale.current
        //numberFormatter.maximumFractionDigits = 2
        //numberFormatter.maximumIntegerDigits = 6
        
        if let result = numberFormatter.number(from: self) {
            return numberFormatter.string(for: result) ?? "0"
        }
        return "0"
    }

but it didn't work: Here is the exemple

let xxx : Float =  111.222
        myTextField.text = String(xxx).afficherUnFloat()

I have installed a pod KSNumericTextField, that limit the numbers in the textfield. He display it only if it is locally formatted.

When i run the app, it doesn't diplay 111,222 in a french region, or 111,222 in an arabic one. nothing is dislpayed


Solution

  • Here is finaly a solution:

    extension Float {
        
        func afficherUnFloat() -> String {
            let text : NSNumber = self as NSNumber
            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .decimal
            numberFormatter.locale = .current
            numberFormatter.groupingSeparator = ""
            numberFormatter.maximumFractionDigits = 2 // your choice
            numberFormatter.maximumIntegerDigits = 6 // your choice
    
            let result = numberFormatter.string(from: text) ?? ""
                return result
        }
        
    }
    

    With this, you can format every Float to a localized String, compatible with the keyboard choosen by the user, regardless of his locality or langage. There is no need to force a special keyboard to have a specific decimal separator.

    you can use it like this:

    let myFloat: Float = 111.222
    let myString :String = myFloat.afficherUnFloat()
    

    myString will be displayed as the location requires