Created
February 13, 2015 09:19
-
-
Save thorsummoner/aed154cbba0cf9f61182 to your computer and use it in GitHub Desktop.
Metric Integers - Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import math | |
class MetricInt(int): | |
""" | |
Integer with metric string representation. | |
""" | |
incPrefixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] | |
decPrefixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y'] | |
def __str__(self): | |
""" | |
Convert integer to metric string. | |
http://stackoverflow.com/a/15734251/1695680 | |
""" | |
d = self | |
if self == 0: | |
return str(0) | |
degree = int(math.floor(math.log10(math.fabs(d)) / 3)) | |
prefix = '' | |
if degree!=0: | |
ds = degree/math.fabs(degree) | |
if ds == 1: | |
if degree - 1 < len(self.incPrefixes): | |
prefix = self.incPrefixes[degree - 1] | |
else: | |
prefix = self.incPrefixes[-1] | |
degree = len(self.incPrefixes) | |
elif ds == -1: | |
if -degree - 1 < len(self.decPrefixes): | |
prefix = self.decPrefixes[-degree - 1] | |
else: | |
prefix = self.decPrefixes[-1] | |
degree = -len(self.decPrefixes) | |
scaled = float(d * math.pow(1000, -degree)) | |
s = "{scaled} {prefix}".format(scaled=scaled, prefix=prefix) | |
else: | |
s = "{d}".format(d=int(d)) | |
return(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see hgrecco/pint#237