rounding numbers up in javascript having problems
本问题已经有最佳答案,请猛点这里访问。
嘿,我对数字的取整有问题,因为我不知道该怎么做。这是数学中使用的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var lon1 = position.coords.longitude* 0.0174532925; var lat1 = position.coords.latitude * 0.0174532925; var i = 0; while (i<locations.length) { x.innerHTML+="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英里。
任何帮助都会非常感谢,提前谢谢。
1 2 3 4 | // Round towards nearest multiple of 0.1 function round(x) { return Math.round(x * 10) / 10; } |
1 | x.innerHTML+="Distance" + round(calcDist(lon1, lat1, locations[i][1]* 0.0174532925, locations[i][2]* 0.0174532925)); |
1 2 3 4 5 6 7 8 | // 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数目
1 2 3 4 5 6 7 8 9 | 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.round()!