Skip to content

Instantly share code, notes, and snippets.

@ladyrassilon
Created November 10, 2015 19:03
Show Gist options
  • Save ladyrassilon/b6d8f7b49e051e0b4059 to your computer and use it in GitHub Desktop.
Save ladyrassilon/b6d8f7b49e051e0b4059 to your computer and use it in GitHub Desktop.
Simplifies "messy" large numbers
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)
@stuaxo
Copy link

stuaxo commented Nov 11, 2015

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 -

In [1]: from decimal import *
In [7]: d = Decimal(-16.0/7)
In [8]: d
Out[8]: Decimal('-2.28571428571428558740308289998210966587066650390625')

In [9]: Decimal(d).quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
Out[9]: Decimal('-2.29')

@ladyrassilon
Copy link
Author

@stuaxo the issue was more trying to create a fixed rounding point....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment