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

1.1k Views Asked by At

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

2

There are 2 best solutions below

2
Wahib On BEST ANSWER

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

2
Leo Dabus On

Note that there is no need to cast your Float to NSNumber. You can use Formatter's method string(for: Any) instead of NumberFormatter's method string(from: NSNumber). Btw it will create a new number formatter every time you call this property. I would make your formatter static:

extension Formatter {
    static let decimal: NumberFormatter = {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        numberFormatter.locale = .current
        numberFormatter.maximumFractionDigits = 2 // your choice
        numberFormatter.maximumIntegerDigits = 6 // your choice
        return numberFormatter
    }()
}
extension FloatingPoint {
    var afficherUnFloat: String { Formatter.decimal.string(for: self) ?? "" }
}

let float: Float = 111.222
let string = float.afficherUnFloat // "111.22"