PHP not support double
I have written one function which is giving diff out put in PHP and Java. Please help me to get same output in PHP too. below are that functions written in both languages.
Function in Java:
public String getLat(String v_str, String strNS){
try
{
double lat = Integer.parseInt(v_str.substring(0, 2));
//System.out.println("lat="+lat);
double lat2 = Float.parseFloat(v_str.substring(2));
lat2 = lat2*10000;
lat2 = lat2/60*10000;
lat2 = lat2/100000000;
//System.out.println("lat2="+lat2);
lat += lat2;
if(strNS.equals(开发者_如何转开发"S"))
return ("-"+lat);
else
return (""+lat);
}
catch(Exception e){}
return ("");
}
Call: getLat("5224.09960","N");
Output: 52.40165999730428
Function in PHP:
$deg_coord = '5224.09960';
$lat = (int)(substr($deg_coord,0,2));
$lat2 = (substr($deg_coord,2));
$lat2 = $lat2*10000;
$lat2 = $lat2/60*10000;
$lat2 = $lat2/100000000;
echo $lat += $lat2;
exit;
Output: 52.40166
It looks like your Java answer is incorrect due to a rounding error. This could be because you use Float instead of Double as float's precision is much more limited than double.
public static void main(String[] args) {
System.out.println(getLat("5224.09960","N"));
}
public static double getLat(String v_str, String strNS) {
double lat = Integer.parseInt(v_str.substring(0, 2));
double lat2 = Double.parseDouble(v_str.substring(2));
lat += lat2 / 60;
return strNS.equals("S") ? -lat : lat;
}
prints
52.40166
I suspect using string manipulation is unsafe as latitudes start at 0. i.e. it only happens to work for numbers with 4 digits in front of the decimal point.
This code makes no assumptions about the number of digits. (It does assume you want to round to 6 decimal places)
public static double getLat(String v_str, String strNS) {
double v = Double.parseDouble(v_str);
double lat = ((long) v)/100;
double lat2 = (v - lat * 100) / 60;
double lat3 = lat + lat2;
double rounded = (double)(long) (lat3 * 1000000 + 0.5) / 1000000;
return strNS.equals("S") ? -rounded : rounded;
}
If you want to reproduce the same rounding error in PHP, you could try
$deg_coord = '5224.09960';
$lat = (int)(substr($deg_coord,0,2));
$lat2 = (float) (substr($deg_coord,2));
$lat2 = $lat2*10000;
$lat2 = $lat2/60*10000;
$lat2 = $lat2/100000000;
echo $lat += $lat2;
exit;
精彩评论