Reputation: 11477
Given a Decimal
number in python how can I find the number of digits past the decimal point?
assert digits(Decimal('1.2345')) == 4
assert digits(Decimal('1000')) == 0
assert digits(Decimal('1.00')) == 2
assert digits(Decimal('1E+5')) == 0
assert digits(Decimal('1.2E+5')) == 0
Upvotes: 5
Views: 3713
Reputation: 11477
After a bit of experimentation, this seems to work correctly:
def digits(n):
return max(0,-n.as_tuple().exponent)
Upvotes: 4
Reputation: 19347
I'll just outline a possible algorithm, assuming you start with a string.
'E'
or the end of the string. If there is no decimal point, the count is zero.'E'
and convert to integer. If there is no 'E'
, that's zero.'2E-2'
would have two decimal places, '1.2E+5'
would have none, and the rather silly '0.02E2'
would have none.Upvotes: 2