0

hey i am having problems with rounding up numbers because Im not sure how i would go about doing it this is the code is use for the maths:

    var lon1 = position.coords.longitude* 0.0174532925;
    var lat1 = position.coords.latitude * 0.0174532925;
    var i = 0;

    while (i<locations.length)
    {
        x.innerHTML+= "<br>Distance " + calcDist(lon1, lat1, locations[i][1]* 0.0174532925, locations[i][2]* 0.0174532925);
        i++;
    }       
    }   
    function calcDist(lon1, lat1, lon2, lat2)
    {
        return Math.acos(Math.sin(lat1)*Math.sin(lat2) + 
        Math.cos(lat1)*Math.cos(lat2) *
        Math.cos(lon2-lon1)) * 3958;    
    }

the reason i am asking is because i am creating a store locator and this is for the distance between the two points the user and the store but when it works it out it shows as 5.595255493978103 instead of 5.6 miles

any help would be much appreciated thanks in advance

Pazrat
  • 103
  • 1
  • 1
  • 9

3 Answers3

1
// Round towards nearest multiple of 0.1
function round(x) {
    return Math.round(x * 10) / 10;
}

x.innerHTML+= "<br>Distance " + round(calcDist(lon1, lat1, locations[i][1]* 0.0174532925, locations[i][2]* 0.0174532925));
Deestan
  • 16,738
  • 4
  • 32
  • 48
0
 // Round towards nearest multiple of 0.1
 function round(num){
     return Math.round(num*10)/10;
 }

So...
round(3.14) = 3.1;
round(3.15) = 3.2;

Or for custom number of dps

function round (num,dp){
  var scale = Math.pow(10,dp);
  return Math.round(num*scale)/scale;
}

So...
round(3.456,2) = 2.46;
round(3.456,1) = 2.5;
roudn(3.456,0) = 2;
Chris Charles
  • 4,406
  • 17
  • 31
-1

you can use Math.round() on values you intended to round!

Moax6629
  • 378
  • 4
  • 14