2017-01-21 80 views
0

我需要在當前應用程序中顯示當前的海拔高度。但是,當確定海拔高度時,標籤會顯示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

+1

使用'NumberFormatter' – vadian

回答

0

試試這個:

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) 
+0

學習做本地化正確。使用'NumberFormatter'。 – Sulthan