Vyacheslav Vyacheslav - 2 months ago 15
Swift Question

NSNumberFormatter for degrees' values

Is there any proper implementation for

0°00'00.00"
format?
NSNumberFormatter
supports only
groupingSeparator
and
decimalSeparator
.
Or not?

Answer

There is no degree-minute-second formatter in Foundation but it's not too hard to roll your own. Here's my crude attempt:

class DegreeFormatter : NumberFormatter {
    func string(from degree: Double) -> String {
        var remaining = degree

        let degree = remaining.rounded(.towardZero)
        remaining -= degree
        remaining *= 60.0

        let minute = remaining.rounded(.towardZero)
        remaining -= minute
        remaining *= 60

        let seconds = remaining

        return "\(Int(degree))°\(Int(minute))'\(self.string(from: seconds as NSNumber)!)"
    }
}

let formatter = DegreeFormatter()
formatter.maximumFractionDigits = 2

print(formatter.string(from: 1.23456789)) // 1°14'4.44

You can customize it further to include custom degree symbols, whether to include the second, what units are allowed, etc.