Created
November 10, 2015 19:03
-
-
Save ladyrassilon/b6d8f7b49e051e0b4059 to your computer and use it in GitHub Desktop.
Simplifies "messy" large numbers
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
from decimal import Decimal, DecimalTuple | |
NUMBER_EXPONENT_PLACES = 4 | |
def clean_exponent(number, places=NUMBER_EXPONENT_PLACES, round_up=True): | |
""" | |
Simplifies messy large numbers | |
Example | |
number = 345464354 | |
places = 2 | |
return = 340000000 | |
""" | |
input_type = type(number) | |
dec_tuple = Decimal(number).as_tuple() | |
clean_digits = [0 for _ in range(len(dec_tuple.digits))] | |
for idx, digit in enumerate(dec_tuple.digits): | |
if idx < places: | |
clean_digits[idx] = digit | |
elif round_up and digit > 5: | |
clean_digits[idx-1] += 1 | |
else: | |
break | |
kwargs = { | |
"sign": dec_tuple.sign, | |
"digits": clean_digits, | |
"exponent": dec_tuple.exponent, | |
} | |
clean_tuple = DecimalTuple(**kwargs) | |
clean_decimal = Decimal(clean_tuple) | |
return input_type(clean_decimal) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hm, iterating all digits in python sets off my 'is it optimal?' spidey-sense...
googling got me here
https://gist.github.com/jackiekazil/6201722
Where examples use the decimal library itself -
Using option #2 you can do something like -