# Jason’s Ranting & Raving

## Perl: Converting Decimal to Degrees Minutes Seconds (and vice-versa)

Posted by jaystile on February 21, 2009

Here is some code I playing with trying to get conversion from one coordinate system to another. There is some percision loss due to the floating point math in the conversions. So expect to see a loss of a few seconds when converting from decimal.

``` 1 #!/usr/bin/perl 2 3 use strict; 4 use POSIX qw(ceil floor); 5 6 # flush print to the output after every write. 7 \$| = 1; 8 9 testConvertDegMinSecToDecimal(); 10 testConvertDecimalToDegMinSec(); 11 12 ##### TEST ROUTINES 13 sub testConvertDegMinSecToDecimal { 14 my \$result = convertDegMinSecToDecimal(121, 8, 6); 15 print "RESULT: \$result\n"; 16 17 my \$result = convertDegMinSecToDecimal(121, 59, 59); 18 print "RESULT: \$result\n"; 19 } 20 21 sub testConvertDecimalToDegMinSec { 22 my \$deg; my \$min; my \$sec; 23 (\$deg, \$min, \$sec) = convertDecimalToDegMinSec(121.135); 24 print "RESULT - DEG: \$deg MIN: \$min SEC: \$sec\n"; 25 26 (\$deg, \$min, \$sec) = convertDecimalToDegMinSec(121.99317); 27 print "RESULT - DEG: \$deg MIN: \$min SEC: \$sec\n"; 28 } 29 30 ##### SUB ROUTINES 31 sub convertDegMinSecToDecimal { 32 my \$deg = \$_; 33 my \$min = \$_; 34 my \$sec = \$_; 35 36 my \$result = \$deg + (\$min/60) + ((\$sec/60) *(1/60)); 37 \$result = sprintf("%.5f", \$result); 38 } 39 40 sub convertDecimalToDegMinSec { 41 my \$input = \$_; 42 my \$deg = floor(\$input); 43 44 \$input = \$input - \$deg; 45 \$input = \$input * 60; 46 47 my \$min = floor(\$input); 48 49 \$input = \$input - \$min; 50 \$input = \$input * 60; 51 52 my \$sec = floor(\$input); 53 54 return (\$deg, \$min, \$sec); 55 } ```

If you’re playing with degrees minutes seconds & decimal degree conversions you’re probably interested in calculating distance on the Earth. There are two common algorithms for calculating distance that are available as CPAN modules: