-1

What is the easiest way in python to count the number of digits after the decimal point for a value < 1 without using string-functions?

For example i have one of the following values: 0.0001 or 0.1001 or 0.1234.

The result in all cases should be 4.

Egirus Ornila
  • 1,234
  • 4
  • 14
  • 39

2 Answers2

1

You can do like this:

>>> x, i = 0.345223, 0
>>> while x*(10**i)//1 - x*(10**i) != 0: i+= 1
... 
>>> i
6
Vicrobot
  • 3,795
  • 1
  • 17
  • 31
0

You could do a quick math trick and multiply by 10 until the number is equal to 1 or greater:

i
0.0001

count
0

while i < 1:
i = i*10
  count += 1

count
4
Kris
  • 420
  • 2
  • 11
  • This is the number of zeroes after the decimal point, not the number of digits. – Barmar Jan 13 '20 at 16:09
  • Another answer can be found (here)[https://stackoverflow.com/questions/6189956/easy-way-of-finding-decimal-places] – Kris Jan 13 '20 at 16:09
  • 1
    my question was not exact enough, i corrected it now. – Egirus Ornila Jan 13 '20 at 16:09
  • for clarification: this *only* works for numbers between 0 and 1, and will not count values after the first non-zero in the decimal. – Kris Jan 13 '20 at 16:10