int vs float divide: abbreviating numbers w/SI units
Bengt Richter
bokr at accessone.com
Sun Jul 29 03:33:23 EDT 2001
On Sat, 28 Jul 2001 12:29:30 -0700, David Eppstein <eppstein at ics.uci.edu> wrote:
>Some time buried in the recent division flamewar I posted a message listing
>the uses I'd recently made of integer division, one of which was some short
>code for abbreviating numbers like 1008926 to e.g. 988k for more readable
>text output of file sizes in a web photo gallery generator.
>
>Anyway, I decided it would be a good idea to make it more general and
>robust, and discovered somewhat to my surprise that float division seems to
>be a better fit for the task. The new code is below if anyone wants to
>critique or use it.
>
[...]
I was going to make a one-liner, but it would be really ugly and repeat stuff ;-)
But there might be something in this you can use?:
import math
def abbrn(n,k=1000):
if n==0: return '0'
nk, rk = divmod(math.log(abs(n)), math.log(k))
nkr = max(-9, min(int(nk), 9))
suffix= 'kyzafpnum kMGTPEZYk'[nkr+9] + (abs(nkr)==9)*("^%d" % (nk,) )
sr = ("%1.1f" % (math.exp(rk),))
adjlen = len(sr) - 2*(sr[-1]=='0' or len(sr)>3)
return '-'*(n<0) + sr[0:adjlen] + suffix
I think it does what yours does, except I rely on %1.1f to round and
just chuck the '.0' or .x if there's more than 3 chars, which makes
some differences, e.g.,
for the args 2.0*10.**-30 1000
yours => 2.0k^-10
mine => 2k^-10
whereas
for the args 2.0*10.**30 1000
yours => 2k^10
mine => 2k^10
JFTHOI-ly ;-)
More information about the Python-list
mailing list