Vyacheslav Vyacheslav - 1 year ago 124
Swift Question

NSNumberFormatter for degrees' values

Is there any proper implementation for

supports only
Or not?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download