Here I got attribute column of bearings for some lines in "Decimal Degree" and I want to convert them to "Degree Minute Second" with each unit in a separate attribute column.
The conversion factor is as follow:-
- 1° = 60'
- 1' = 60"
- 1° = 3600"
Note that the bearings where generated using the azimuth expression listed below:-
degrees( azimuth( start_point($geometry), end_point($geometry) ) )
The conversion
As an example, lets convert this 104.580420 (which is in Decimal Degree) to Degree Minute Second.
- Degree = INT(104.580420) = 104°
- Minute = INT((104.580420 - 104) * 60) = 34'
- Seconds = (34.82520000000022 - 34) * 60 = 49.512"
Therefore, the result of 104.580420 is: 104° 34' 49.512"
brg = 104.580420
try:
# Making sure the brg is a float number...
brg = float(brg)
# Degree...
brg_degree = int(brg)
# Minute
brg_minute = int((brg - brg_degree) * 60)
# Second
brg_second = round( (((brg - brg_degree) * 60) - brg_minute) * 60, 2)
# Display or return the result...
print(str(brg_degree) +'° '+ str(brg_minute) +"' "+ str(brg_second) +'" ')
except ValueError:
print('Error: Invalid Bearing')
from qgis.core import *
from qgis.gui import *
@qgsfunction(args='auto', group='Custom')
def bearing_func(brg, feature, parent):
try:
# Making sure the brg is a float number...
brg = float(brg)
# Degree...
brg_degree = int(brg)
# Minute
brg_minute = int((brg - brg_degree) * 60)
# Second
brg_second = round( (((brg - brg_degree) * 60) - brg_minute) * 60, 2)
# Display or return the result...
return str(brg_degree) +'° '+ str(brg_minute) +"' "+ str(brg_second) +'"'
except ValueError:
return 'Error: Invalid Bearing'
Note that the output field type is set to 'Text (String)' because of the symbols used in the result.
That is it!