2011-08-04 60 views
1

我在谷歌地图应用程序中的下面,并希望显示高度转换为英尺,但我怎么向上/向下舍入到最近的数字? (消除十进制数字后)我尝试了number.toFixed(x)方法,但似乎没有做到这一点。舍入数字javascript - 数学

function getElevation(event) { 

    var locations = []; 
    var clickedLocation = event.latLng; 
    locations.push(clickedLocation); 
    var positionalRequest = { 'locations': locations } 

    // Initiate the location request 
    elevator.getElevationForLocations(positionalRequest, function(results, status) { 
     if (status == google.maps.ElevationStatus.OK) { 

     // Retrieve the first result 
     if (results[0]) { 

      // Open an info window indicating the elevation at the clicked position 
      infowindow.setContent("The elevation at this point <br/>is " + results[0].elevation*(3.2808399) + " feet."); 
      infowindow.setPosition(clickedLocation); 
      infowindow.open(map); 
     } else { 
      alert("No results found"); 
     } 
     } else { 
     alert("Elevation service failed due to: " + status); 
     } 
    }); 
    } 

回答

2

如果要舍入到最接近的整数,只需使用Math.round(x)

Math.round(25.9) //returns 26 
Math.round(25.2) //returns 25 
Math.round(-2.58) //returns -3 

您可能还需要寻找到Math.floor(总是下舍)和Math.ceil(总是四舍五入)。

我已经把它演示所有三种方法小提琴:jsFiddle

+0

谢谢你。结束于'Math.round(results [0] .elevation *(3.2808399))+“英尺”。)'' – RonnieT

1

Math.floor(n)

返回数字四舍五入到最接近的整数

Math.ceil(n)

返回数字四舍五入到最接近的整数

Math.round(n)

返回四舍五入到最接近整数的数字