【问题标题】:How do I append Altitude Integers如何附加海拔整数
【发布时间】:2017-01-21 21:05:32
【问题描述】:

我需要在我正在构建的当前应用中显示当前高度。但是,当高度确定时,标签会显示为 xxx.xxxxxxxxxxxx 它在小数点的另一边走得很远。我只希望它在小数点的另一侧最多给出 2 个数字。这怎么可能?

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

     func locationManager(_ manager: CLLocationManager,            didUpdateLocations locations: [CLLocation]) {

    let location = locations [0]

    self.speedLabel.text = String(location.speed)


    self.altitudeLabel.text = String(location.altitude)
    CLGeocoder().reverseGeocodeLocation(location) { (placemarks, error) in

        if error != nil {
            print(error!)

        }

这是我当前的代码。

就像我说的,我只想将高度显示为“XX.XX”而不是 XX.XXXXXXXXX

【问题讨论】:

  • 使用NumberFormatter

标签: swift xcode swift3 mapkit cllocationmanager


【解决方案1】:

试试这个:

extension Double {
    func decimal(places: Int) -> Double {
        let resultString = NSString(format: "%.\(places)f" as NSString, self) as String
        return Double(resultString)!
    }
}

self.altitudeLabel.text = location.altitude.decimal(places: 2)

【讨论】:

    【解决方案2】:

    试试吧:

    self.altitudeLabel.text = String(format: "%.2f", location.altitude)
    

    【讨论】:

    • 学习正确地进行本地化。使用NumberFormatter
    猜你喜欢
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 2020-10-06
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多