0

嘿,我在四舍五入时遇到问题,因为我不确定我将如何去做这是用于数学的代码:

    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;    
    }

我问的原因是因为我正在创建一个商店定位器,这是针对用户和商店两点之间的距离,但是当它计算出来时,它显示为 5.595255493978103 而不是 5.6 英里

任何帮助将不胜感激提前感谢

4

3 回答 3

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));
于 2013-09-26T09:07:52.780 回答
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;

或者自定义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;
于 2013-09-26T09:17:45.287 回答
-1

您可以在要舍入的值上使用 Math.round() !

于 2013-09-26T09:13:54.570 回答