Created
October 5, 2017 11:14
-
-
Save truongduyng/0d9b5ecce5312e86934320e8dedc67ce to your computer and use it in GitHub Desktop.
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
import math | |
import decimal | |
def pretty_print(value): | |
value = float(value) | |
bias = 0 | |
intdigits = math.floor(math.log10(value)) | |
divisor = 0 | |
if intdigits >= 3: | |
divisor = intdigits - (intdigits%3) | |
# print "Divisor", divisor, "Int digits", intdigits, "Value", value | |
value = value/10**divisor | |
name = getName(intdigits) | |
decValue = decimal.Decimal(value).quantize(decimal.Decimal('.001'), rounding=decimal.ROUND_DOWN) | |
return str(decValue) + name | |
def getName(power): | |
if power >= 12: | |
return "T" | |
elif power >= 9: | |
return "B" | |
elif power >= 6: | |
return "M" | |
elif power >= 3: | |
return "K" | |
else: | |
return "" | |
print pretty_print(1.0), pretty_print(1.0) == '1.000' | |
print pretty_print(100), pretty_print(100) == '100.000' | |
print pretty_print(10), pretty_print(10) == '10.000' | |
print pretty_print(1000000), pretty_print(1000000) == '1.000M' | |
print pretty_print(1000000000), pretty_print(1000000000) == '1.000B' | |
print pretty_print(10.0000000), pretty_print(10.0000000) == '10.000' | |
print pretty_print(10.11111), pretty_print(10.11111) == '10.111' | |
print pretty_print(10.00001), pretty_print(10.00001) == '10.000' | |
print pretty_print(100000143), pretty_print(100000143) == '100.000M' | |
print pretty_print(10327492), pretty_print(10327492) == '10.327M' | |
print pretty_print(103272), pretty_print(103272) == '103.272K' | |
print pretty_print(103274932), pretty_print(103274932) == '103.274M' | |
print pretty_print(1032742192), pretty_print(1032742192) == '1.032B' | |
print pretty_print(1032142192), pretty_print(1032142192) == '1.032B' | |
print pretty_print(1032192), pretty_print(1032192) == '1.032M' | |
print pretty_print(10321647193342), pretty_print(10321647193342) == '10.321T' | |
print pretty_print(24781894), pretty_print(24781894) == '24.781M' | |
print pretty_print(612481894), pretty_print(612481894) == '612.481M' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment