swiftdigitsnsnumberformatter

Swift: just 1 fractional digits for NSLengthFormatter


I use the NSLengthFormatter to show the right entity like meters, feets, yards etc.
The method works, but I don't get the right quantity of fractional digits.

let distance = getDistanceAsDouble() //636.62084358567 in meters
        let format = String(format: "%.1f",distance) //636.6

        if let formattedDouble = Double(format) {
            let lengthFormatter = NSLengthFormatter()
            let formattedDistance = lengthFormatter.stringFromMeters(formattedDouble) 
            lbl.text = "\(formattedDistance)" // printed: 697.936 yd
        }

I googled, but I can't find how configure the NSLengthFormatter. The NSNumberFormatter has properties like numberStyle or maximumFractionDigitis, but NSLengthFormatter hasn't... or?

I tried to cast formattedDistance to Double that I can use String(format: ""... again. This doesn't work because formattedDistance contains "yd" (or another entity).

How can I fix this problem?


Solution

  • NSLengthFormatter has a property numberFormatter: NSNumberFormatter, so use that to set it, like so...

    if let formattedDouble = Double(format) {
        let lengthFormatter = NSLengthFormatter()
        lengthFormatter.numberFormatter.maximumFractionDigits = 1 // *****
        let formattedDistance = lengthFormatter.stringFromMeters(formattedDouble)
        print("\(formattedDistance)") 
    }