ios - Calculating Distance, converting to km and then cutting out decimal places -


edit 3: thank beyowulf, implemented line of code , result! hoping for. thank suggestions.

edit 2: interesting, per user27388882 suggestion changed code to:

//convert kilometers let kilometers = double(round(traveleddistance) / 1000) 

the result 3 decimal places. ideally 2 @ most, step in right direction! thank you!

edit 1: clarification of "does not work": guess can't post picture, here link when viewed in simulator. the distance still appears super long string of decimals, despite using code try , shorten number of decimal places. perceive not working in code decimal places should cut off.

i creating app tracks users location while riding bicycle. 1 feature take distance travelled user , display in km. have gotten distance function work searching through other posts. have looked @ nsnumberformatter documents, implementing code have seen not work. issue of distance being double calculated cllocation? piece of potentially relevant information working in xcode 7.2 , swift2.

i don't want post whole code since want highlight stuck, not sure if more of code needed solve this.

import uikit import corelocation  // global variables  var startlocation:cllocation! var lastlocation: cllocation! var traveleddistance:double = 0   // identify labels @iboutlet weak var distancelabel: uilabel!  // create location manager func locationmanager(manager: cllocationmanager, didupdatelocations locations: [cllocation]) {  //calculate distance between points total distance traveled... if startlocation == nil {     startlocation = locations.first! cllocation } else {     let lastlocation = locations.last! cllocation     let distance = startlocation.distancefromlocation(lastlocation)     startlocation = lastlocation     traveleddistance += distance      //convert kilometers     let kilometers = traveleddistance / 1000       //convert 2 decimal places     let nf = nsnumberformatter()     nf.minimumsignificantdigits = 1     nf.maximumfractiondigits = 2     nf.numberstyle = .decimalstyle      nf.stringfromnumber(kilometers)      //update distance label     self.distancelabel.text = "\(kilometers) kilometers" 

help me, stackoverflow. you're hope.

tl;dr round out decimal places distance value calculated user location using swift2.

shouldn't wait round until ready display results? can like:

let formatedstring = string(format:"%.2f",float(traveleddistance / 1000.0 + .005)) 

to traveleddistance rounded neared hundredth of kilometer.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -