Im trying to write a function that takes my decimal degrees (lat or long) and converts them to DMS degrees minutes seconds. I know I am meant to times the decimal point number by 60 then it's decimal again. But am a noob. Would I split the number?
function ConvertDDToDMS(DD) {
eg. DD =-42.4
D= 42;
M= 4*60;
S= .M * 60;
var DMS =
return DMS //append Direction (N, S, E, W);
}
Am I on the right track?
function ConvertDDToDMS(D, lng){
const M=0|(D%1)*60e7;
return {
dir : D<0?lng?'W':'S':lng?'E':'N',
deg : 0|(D<0?D=-D:D),
min : 0|M/1e7,
sec : (0|M/1e6%1*6e4)/100
};
}
The above gives you an object {deg:, min:, sec:, dir:}
with sec truncated to two digits (e.g. 3.14
) and dir being one of N
, E
, S
, W
depending on whether you set the lng
(longitude) parameter to true. e.g.:
ConvertDDToDMS(-18.213, true) == {
deg : 18,
min : 12,
sec : 46.79,
dir : 'W'
}
Or if you just want the basic string:
function ConvertDDToDMS(D){
return [0|D, 'd ', 0|(D<0?D=-D:D)%1*60, "' ", 0|D*60%1*60, '"'].join('');
}
ConvertDDToDMS(-18.213) == `-18d 12' 46"`
[edit June 2019] -- fixing an 8 year old bug that would sometimes cause the result to be 1 minute off due to floating point math when converting an exact minute, e.g. ConvertDDToDMS(4 + 20/60)
. Updated code still has a slight issue, but will round to 19min 59.99 sec in this case, which is fine and not fixable due to the way floating points work