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
I like the name "metric".
Maybe a very minimal pip package could be a good idea.
if you never did a package before you can have a look at 2 of my projects
https://github.com/scls19fr/openweathermap_requests
https://github.com/scls19fr/pandas_degreedays
Add some unit tests and ensure that it also works fine with several Python version
(Travis can help)
if I were you I will keep ToSI a function and provide MetricInt, MetricFloat, MetricDouble, MetricDecimal.
Adding units could be a great idea.
But maybe we should see with Pint http://pint.readthedocs.org/