Convert decimal degrees to DMS in QGIS

I often need to provide coordinates to light aircraft pilots – and most of them still use degree-minute-second notation (DMS) for charts and GPS. If we can’t upload flight plans and waypoints directly to the GPS I need to provide tables of DMS points – while QGIS can display in DMS in the canvas, it doesn’t have built-in functions for calculating and filling attribute fields.

A user shared part of the code for this last year, and with QGIS 1.9 the floor() function in the field calculator lets it work properly.

  1. Add your latlong point file to QGIS (or save-as in latlong then open it);
  2. Open the attribute table and start editing, then open the field calculator;
  3. Create a new text field of length 16, named ‘lon_dms’, and enter the code below in the ‘Expression’ box;
  4. Calculate, then repeat for ‘lat_dms’ but change each $x to $y.
  5. Save.

Edit 2017-01-16 – thanks to Skippy for pointing out the southern hemisphere error in the DMS coordinates. Here’s a better version for more general usage, giving N and S labels for latitude:

(CASE WHEN $y < 0 THEN 'S' ELSE 'N' END) || floor (abs($y)) || '°' || floor(((abs($y)) - floor (abs($y))) * 60) ||'\'' || substr( (tostring((((abs($y)) - floor (abs($y))) * 60) - floor(((abs($y)) - floor (abs($y))) * 60)) * 60),1,5) || '"'

Original code:

floor ($x) || '°' || floor((($x) - floor ($x)) * 60) ||'\'' || substr( (tostring(((($x) - floor ($x)) * 60) - floor((($x) - floor ($x)) * 60)) * 60),1,5) || '"'

Input: 123.12345° 

Output: 123°7’24.42″