Swift: only 1 fractional digit for NSLengthFormatter

I use NSLengthFormatter to show the correct entity, e.g. meters, feet, yards, etc.
The method works, but I do not get the correct number 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 not find how to configure NSLengthFormatter. NSNumberFormatter has properties like numberStyleor maximumFractionDigitis, but NSLengthFormatter does not ... or?

I tried using formattedDistancein Double to use again String(format: "".... This does not work because it formattedDistancecontains "yd" (or another object).

How can I fix this problem?

+4
source share
1 answer

NSLengthFormatterhas a property numberFormatter: NSNumberFormatter, so use it to set it, for example ...

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

Source: https://habr.com/ru/post/1620711/


All Articles