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

Given the Decimal number in python, how can I find the number of digits after 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 
+4
source share
2 answers

After several experiments, this looks right:

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

I will just describe a possible algorithm, assuming you start with a line.

  • Starting on the left, find the decimal point. Count the numbers between them and either the 'E' or the end of the line. If there is no decimal point, the counter is zero.
  • Parse the value following 'E' and convert to an integer. If there is no 'E' , then zero.
  • Subtract the second from the first of two values; the maximum of this and zero is the result. So, '2E-2' will have two decimal places, '1.2E+5' will not have any meaning, and pretty dumb '0.02E2' will not.
  • As a degenerate case, zero is likely to have zero decimal positions. As for infinity and any other special values, I don't have a clear opinion about whether these are zero decimal places or not.
+2
source

Source: https://habr.com/ru/post/1483176/


All Articles