Justin Petty - 1 year ago 87

PHP Question

My question is how would I round the output of The script below to display 107.4 instead of 107.44613075316 I found the php round function but I'm not sure how to implement it.

`///// Get the two locations from the url`

$lat1 = $_GET[lat1];

$lon1 = $_GET[lon1];

$lat2 = $_GET[lat2];

$lon2 = $_GET[lon2];

//////calculate the distance

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

$theta = $lon1 - $lon2;

$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +

cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));

$dist = acos($dist);

$dist = rad2deg($dist);

$miles = $dist * 60 * 1.1515;

$unit = strtoupper($unit);

if ($unit == "K") {

return ($miles * 1.609344);

} else if ($unit == "N") {

return ($miles * 0.8684);

} else {

return $miles;

}

}

// Miles

echo distance($lat1, $lon1, $lat2, $lon2, "m") . " miles<br><br>";

//Kilometers

echo distance($lat1, $lon1, $lat2, $lon2, "k") . " kilometers<br><br>";

//Nautical miles

echo distance($lat1, $lon1, $lat2, $lon2, "N") . " Nautical miles";

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The PHP manual is very clear in how to use the round() method.

The simplest way to round it automatically would be within your distance function, although it's arguable that you would want full precision from this method.. If you don't, then use the following which will automatically round the output:

```
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +
cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
$output = $miles;
if ($unit == "K") {
$output = $miles * 1.609344;
} else if ($unit == "N") {
$output = $miles * 0.8684;
}
return round($output, 1);
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**