I am looking for an elegant way to pretty-print physical quantities with the most appropriate prefix (as in 12300 grams
are 12.3 kilograms
). A simple approach looks like this:
def pprint_units(v, unit_str, num_fmt="{:.3f}"):
""" Pretty printer for physical quantities """
# prefixes and power:
u_pres = [(-9, u'n'), (-6, u'µ'), (-3, u'm'), (0, ''),
(+3, u'k'), (+6, u'M'), (+9, u'G')]
if v == 0:
return num_fmt.format(v) + " " + unit_str
p = np.log10(1.0*abs(v))
p_diffs = np.array([(p - u_p[0]) for u_p in u_pres])
idx = np.argmin(p_diffs * (1+np.sign(p_diffs))) - 1
u_p = u_pres[idx if idx >= 0 else 0]
return num_fmt.format(v / 10.**u_p[0]) + " " + u_p[1] + unit_str
for v in [12e-6, 3.4, .123, 3452]:
print(pprint_units(v, 'g', "{: 7.2f}"))
# Prints:
# 12.00 µg
# 3.40 g
# 123.00 mg
# 3.45 kg
Looking over units and Pint, I could not find that functionality. Are there any other libraries which typeset SI units more comprehensively (to handle special cases like angles, temperatures, etc)?
a=4.0
a = a / 3.0
print(pprint_units(a, 'g', "{: 7.2f}"))
? I cannot give an answer without knowing that. – Trunnelpprint_units(4./3, 'g', "{: 7.2f}")
should result in' 1.33 g'
. – Metal