For American numbers
Nick Coghlan
ncoghlan at iinet.net.au
Sat Feb 12 22:49:30 EST 2005
Scott David Daniels wrote:
> Kind of fun exercise (no good for British English).
>
> def units(value, units='bytes'):
> magnitude = abs(value)
> if magnitude >= 1000:
> for prefix in :
> magnitude /= 1000.
> if magnitude < 1000.:
> break
> elif magnitude < 1:
> for prefix in :
> magnitude *= 1000.
> if magnitude >= 1.0:
> break
> if magnitude < .001:
> return 'zero %s' % units
> else:
> prefix = ''
> if value < 0:
> return '-%.3f %s%s' % (magnitude, prefix, units)
> return '%.3f %s%s' % (magnitude, prefix, units)
>
> --Scott David Daniels
> Scott.Daniels at Acm.Org
>
Because I can't resist generalising this. . .
def units(value, units='bytes', base=1000.0,
super_prefixes = ('kilo mega giga tera peta '
'exa zetta yotta').split(),
sub_prefixes = ('milli micro nano pico femto '
'atto zepto yocto').split()):
magnitude = abs(value)
if magnitude >= base:
for prefix in super_prefixes:
magnitude /= base
if magnitude < base:
break
elif magnitude < 1.0:
for prefix in sub_prefixes:
magnitude *= base
if magnitude >= 1.0:
break
if not sub_prefixes or magnitude < .001:
return 'zero %s' % units
else:
prefix = ''
if value < 0:
return '-%.3f %s%s' % (magnitude, prefix, units)
return '%.3f %s%s' % (magnitude, prefix, units)
def bytecount(value):
# Should check if these prefixes are right. . .
return units(value, 'bytes', 1024.0,
'kibi mebi gibi tebi pebi ebi zebi yobi'.split(), [])
Py> for i in range(1, 28, 3):
... print units(10**i)
... print bytecount(10**i)
...
10.000 bytes
10.000 bytes
10.000 kilobytes
9.766 kibibytes
10.000 megabytes
9.537 mebibytes
10.000 gigabytes
9.313 gibibytes
10.000 terabytes
9.095 tebibytes
10.000 petabytes
8.882 pebibytes
10.000 exabytes
8.674 ebibytes
10.000 zettabytes
8.470 zebibytes
10.000 yottabytes
8.272 yobibytes
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-list
mailing list