Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print negative zero in Python

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

like image 882
Nick Coleman Avatar asked May 24 '13 11:05

Nick Coleman


Video Answer


2 Answers

Use format()

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


>>> print '''{: g}°{}'{}"'''.format(-0.0, 23, 29)
-0°23'29"
like image 159
John La Rooy Avatar answered Sep 18 '22 14:09

John La Rooy


You must print the degrees as a floating point value, not as an integer, as 2 complement integers (used on most platforms) do not have a negative zero. %d is for formatting integers.

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

deg, min and sec are all floats, the fabs calls are there so that the respective signs are not printed.

Alternatively using the old format string style:

print (u'%.0f°%.0f\'%.0f\"' % (deg, fabs(min), fabs(sec))).encode('utf-8')
like image 38
Joe Avatar answered Sep 20 '22 14:09

Joe