For example, the distance is defined by meters.
Procedure should format value on a scale:
if distance < 100:
return '%dm' % distance
elif distance < 1000:
return '%.0fm' % round(distance, -1)
else:
import math
m, km = math.modf(distance / 1000.0)
if m < 0.01:
return '%.0fkm' % km
else:
return '%.1fkm' % km + round(m, 1)
It would be great to use already existing solution.
Update: django-distanceformatting is launched, but the question remains open.
There are some generic unit handling modules for Python, which could be wrapped in a template tag (no specific order):
Maybe one of them gives you what you need. But I still stand to my earlier comment that if you only need so little functionality, you should not need to bother about reinventing the wheel (or your tiny part thereof).
After a closer look at your code, I found some inconsistencies:
Here is a more consistent and concise version of your function (plus a little wrapping around to test):
The first line in the new
dist_format()function always keeps two significant figures. %g leaves out everything from the decimal point if not needed. Caveat: My function will give you exponential notation for (astronomic) distances >= 1000000000.