在javascript中将数字四舍五入有问题

时间:2013-09-26 09:04:35

标签: javascript math

嘿,我在收集数字方面遇到了问题,因为我不知道我会怎么做这个代码用于数学:

    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英里

提前感谢任何帮助

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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;

答案 2 :(得分:-1)

你可以对要打圆的值使用Math.round()!