ios - 计算距离,转换为公里,然后去掉小数位

标签 ios swift

编辑 3:谢谢 beyowulf,我实现了你的代码行,这是 result!正是我所希望的。感谢您的所有建议。

编辑 2:很有趣,根据 user27388882 的建议,我将代码更改为:

//convert to kilometers
let kilometers = Double(round(traveledDistance) / 1000)

结果保留三位小数。理想情况下,我最多只想要两个,但这是朝着正确方向迈出的一步!谢谢!

编辑 1:澄清“不起作用”:我想我不能张贴图片,但在模拟器中查看时,这里有一个链接。 The distance still appears as a super long string of decimals, despite using code to try and shorten the number of decimal places. What I perceive to not be working in my code is where the decimal places should be cut off.

我实际上是在创建一个应用程序来跟踪用户骑自行车时的位置。一项功能是获取用户行驶的距离并以 KM 显示。我已经通过搜索其他帖子获得了距离功能。我也看过 NSNumberFormatter 的帮助文档,但是实现我看到的代码是行不通的。这是从 CLLocation 计算的距离问题吗?另一条可能相关的信息是我在 Xcode 7.2 和 Swift2 中工作。

我不想发布我的整个代码,因为我想突出显示我卡住的地方,但不确定是否需要我的更多代码来解决这个问题。

import UIKit
import CoreLocation

// Global variables

var startLocation:CLLocation!
var lastLocation: CLLocation!
var traveledDistance:Double = 0


// Identify Labels
@IBOutlet weak var distanceLabel: UILabel!

// Create a location manager
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

//Calculate the distance between points as a total distance traveled...
if startLocation == nil {
    startLocation = locations.first! as CLLocation
} else {
    let lastLocation = locations.last! as CLLocation
    let distance = startLocation.distanceFromLocation(lastLocation)
    startLocation = lastLocation
    traveledDistance += distance

    //convert to kilometers
    let kilometers = traveledDistance / 1000


    //Convert to only two decimal places
    let nf = NSNumberFormatter()
    nf.minimumSignificantDigits = 1
    nf.maximumFractionDigits = 2
    nf.numberStyle = .DecimalStyle

    nf.stringFromNumber(kilometers)

    //Update the distance label
    self.distanceLabel.text = "\(kilometers) kilometers"

帮帮我,stackOverFlow。你是我唯一的希望。

tl;dr 从使用 swift2 从用户位置计算的距离值中舍入小数位。

最佳答案

不应该等到您准备好显示结果后再进行舍入吗?你可以这样说:

let formatedString = String(format:"%.2f",Float(traveledDistance / 1000.0 + .005))

要将 traveledDistance 四舍五入到接近百分之一公里。

关于ios - 计算距离,转换为公里,然后去掉小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35234691/

相关文章:

iphone - 什么时候调用 viewWillAppear?

ios - NSCameraUsageDescription 在 Xcode 9 中不起作用

Swift prepareForSegue 到许多自定义 ViewController 之一

ios - 惰性/内联在 Swift 中实现协议(protocol)

Swift:正确解码不精确的十进制

ios - 如何根据按钮的标题设置UIbutton的autoSize?

ios - 在 iOS 中滚动 <div> 会导致 div 空白

ios - 如何在 Swift 4 中的 UIPickerView 中的文本旁边添加图像或图标?

objective-c - 如何快速在捕获的视频/图像上添加叠加文本?

ios - UITableView 只显示 10 个单元格/行