9

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).

4

2 回答 2

17

利用format()

>>> format(-0.0)
'-0.0'
>>> format(0.0)
'0.0'


>>> print '''{: g}°{}'{}"'''.format(-0.0, 23, 29)
-0°23'29"
于 2013-05-24T11:30:40.003 回答
2

您必须将度数打印为浮点值,而不是整数,因为 2 个补码整数(在大多数平台上使用)没有负零。%d用于格式化整数。

print u'{:.0f}°{:.0f}\'{:.0f}\"'.format(deg, fabs(min), fabs(sec)).encode('utf-8')

degmin并且sec都是浮点数,fabs调用在那里,因此不会打印相应的标志。

或者使用旧的格式字符串样式:

print (u'%.0f°%.0f\'%.0f\"' % (deg, fabs(min), fabs(sec))).encode('utf-8')
于 2013-05-24T12:08:03.940 回答