PHP: Convert coordinates from degrees to decimal format

PHP: Convert coordinates from degrees to decimal format



This code will convert longitude and latitude in D'M'S format into a decimal format. It also contains the function to do the reverse.

The example below does contain a couple of strange lines of code. You will notice that we seperate the integer and floating point values from the decimal format using a set of string functions, instead of using the math round or floor functions. This fixes a 'feature' in some versions of PHP that causes it to behave in an unpredictable manner when handling math with floating points.
For example, if you include the code print(91.1 - 91); in PHP you may not get the result you expect. You will actually get 0.099999999999994, not 1 ! This tends to throw of the calculations in the example.

function DMStoDEC($deg,$min,$sec)

// Converts DMS ( Degrees / minutes / seconds )
// to decimal format longitude / latitude

return $deg+((($min*60)+($sec))/3600);


// Converts decimal longitude / latitude to DMS
// ( Degrees / minutes / seconds )

// This is the piece of code which may appear to
// be inefficient, but to avoid issues with floating
// point math we extract the integer part and the float
// part by using a string function.

$vars explode(".",$dec);
$deg $vars[0];
$tempma "0.".$vars[1];

$tempma $tempma 3600;
$min floor($tempma 60);
$sec $tempma - ($min*60);

    return array(




We use our own cookies and third-party cookies to improve our services, show products based on your preferences, analyse the browsing habits of our users, and enable interaction with social networks. Continuing to browse our sites implies full acceptance of their use. You can change your cookie setting or get more information here: Cookies policy .