这里我正在进行两个纬度和经度之间的距离计算。它工作正常。我得到像" 7.4055315795109"但我不想显示这么多小数位。我的预期结果是" 7.4"。我怎样才能达到预期的答案?
我的代码:
<?php
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
{
return $miles;
}
}
// Kilometres
echo distance('12.91747','77.6220413','12.9577129','77.6764937', "K");
?>
答案 0 :(得分:0)
要完成单位精确舍入,您需要内置函数round
应该有所帮助 - 就像这样:
function distance( $lat1, $lon1, $lat2, $lon2, $unit='M' ) {
$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" ) {/* round the output and reduce precision to 1 digit */
return round( ( $miles * 1.609344 ), 1, PHP_ROUND_HALF_UP );
} else {
return round( $miles, 1, PHP_ROUND_HALF_UP );
}
}
echo distance('12.91747','77.6220413','12.9577129','77.6764937', "K");
//outputs 7.4