I am converting decimal degrees to print as DMS. The conversion algorithm is what you would expect, using modf, with the addition that sign is taken out of the MS portion and left in only for the D portion.
Everything is fine except for the case where the Degree is negative zero, -0. An example is -0.391612 which should print as -0°23'29".
"%d" drops the negative sign. What format string can I use to print -0?
I've worked around it with a kludge that converts the numbers to strings and prepends a "-" if negative, then uses "%s" as the format. It's awkward and feels inelegant.
Here's the code:
def dec_to_DMS(decimal_deg):
deg = modf(decimal_deg)[1]
deg_ = fabs(modf(decimal_deg)[0])
min = modf(deg_ * 60)[1]
min_ = modf(deg_ * 60)[0]
sec = modf(min_ * 60)[1]
return deg,min,sec
def print_DMS(dms): # dms is a tuple
# make sure the "-" is printed for -0.xxx
format = ("-" if copysign(1,dms[0]) < 0 else "") + "%d°%02d'%02d\""
return format % dms
print print_DMS(dec_to_DMS(-0.391612))
>>> -0°23'29"
deg_
is to prevent the function returning (-0,-23,-29); it returns the correct (-0,23,29).