kuzdu
kuzdu

Reputation: 7524

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?

Upvotes: 4

Views: 379

Answers (2)

Yurii Samoienko
Yurii Samoienko

Reputation: 89

Swift 5.4.2

if let formattedDouble = Double(format) {
   let lengthFormatter = LengthFormatter()
   lengthFormatter.numberFormatter.maximumFractionDigits = 1 // *****
   let formattedDistance = lengthFormatter.string(fromMeters: formattedDouble)
}

Upvotes: 0

Grimxn
Grimxn

Reputation: 22487

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)") 
}

Upvotes: 6

Related Questions