gerdemb
gerdemb

Reputation: 11477

Find the number of digits in the fractional part of a Decimal number in python

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

Answers (2)

gerdemb
gerdemb

Reputation: 11477

After a bit of experimentation, this seems to work correctly:

def digits(n):
    return max(0,-n.as_tuple().exponent)

Upvotes: 4

wberry
wberry

Reputation: 19347

I'll just outline a possible algorithm, assuming you start with a string.

  • Starting from the left, find decimal point. Count digits between it and either an 'E' or the end of the string. If there is no decimal point, the count is zero.
  • Parse out the value following 'E' and convert to integer. If there is no 'E', that's zero.
  • Subtract the second from the first of the two above values; the maximum of that and zero is the result. So '2E-2' would have two decimal places, '1.2E+5' would have none, and the rather silly '0.02E2' would have none.
  • As a degenerate case, zero itself would probably have zero decimal positions. As for infinity and any other special values, I don't have a strong opinion whether that's zero decimal places or not.

Upvotes: 2

Related Questions