javascript中的四舍五入数字有问题

javascript中的四舍五入数字有问题,javascript,math,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>Distanc

嘿,我在对数字进行取整时遇到了问题,因为我不确定如何进行取整。这是用于数学的代码:

    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;    
    }
var lon1=位置坐标经度*0.0174532925;
var lat1=位置坐标纬度*0.0174532925;
var i=0;
而

x.innerHTML+=“
距离”+圆形(计算列表(lon1,lat1,位置[i][1]*0.0174532925,位置[i][2]*0.0174532925));
您可以对要舍入的值使用Math.round()

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

我可能会使用
Math.ceil
,但在其他方面回答得很好。@DaniëlW.Crompton我正在向最近的数字进位,因为我认为这是他真正想要的。使用
Math.ceil
,记住将
+0.5
调整为
-0.5
,或者如果你想严格取整的话就删除它……或者使用
Ma这一轮
.Derp.忘了那一轮。这一轮非常有效。非常感谢。这一轮非常有效。谢谢
 // 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;
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;