I'm working on a Python script that handles geographic coordinates using the GeoCoordinates class. The class is supposed to convert latitude and longitude from decimal degrees to degrees, minutes, and seconds (DMS) format and vice versa. However, I've encountered an issue where the longitude sign is incorrect in the output. When I create an object with the coordinates lat=40.7775, long=-122.41639, the expected output for longitude should be 40°46′39″N 122°24′59″W, but I'm getting 40°46′39″N -122°24′59″W.
def convert_lat_long_to_dms(self, lat: float, long: float):
lat_deg = int(lat)
lat_min = int((lat - lat_deg) * 60)
lat_sec = round((lat - lat_deg - lat_min / 60) * 3600)
lat_dir = 'S' if lat < 0 else 'N'
long_deg = int(long)
long_min = int((long - long_deg) * 60)
long_sec = round((long - long_deg - long_min / 60) * 3600)
long_dir = 'W' if long < 0 else 'E'
return f"{lat_deg}°{lat_min:02}′{lat_sec:02}″{lat_dir} {long_deg}°{abs(long_min):02}′. {abs(long_sec):02}″{long_dir}"
A short follow-up to hmn Falahi because I don't have enough reputation to comment
Add abs() around
lat_minandlat_secin the return statement. Iflat = -40.7775andlong = -122.41639, convert_lat_long_to_dms will return40°-46′-39″S 122°24′59″Was lat_min and lat_sec are still negative values